ubuntu

Node.js应用在Ubuntu日志中的异常捕获

小樊
36
2025-11-16 06:49:56
栏目: 编程语言

在Node.js应用中,捕获异常并将其记录到Ubuntu日志中是一个很好的实践,可以帮助你监控和调试应用。以下是一些步骤和方法来实现这一点:

1. 使用 process.on('uncaughtException')

这是最基本的异常捕获方法,可以捕获未处理的异常。

process.on('uncaughtException', (err) => {
  console.error('There was an uncaught error', err);
  // 你可以在这里添加更多的逻辑,比如发送邮件通知等
  process.exit(1); // 强制退出进程
});

2. 使用 process.on('unhandledRejection')

这个事件用于捕获未处理的Promise拒绝。

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
  // 你可以在这里添加更多的逻辑,比如发送邮件通知等
});

3. 使用第三方库

有一些第三方库可以帮助你更好地管理和记录异常,比如 winstonpino

使用 winston

const winston = require('winston');

const logger = winston.createLogger({
  level: 'error',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.Console()
  ]
});

process.on('uncaughtException', (err) => {
  logger.error('There was an uncaught error', { error: err });
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error('Unhandled Rejection at:', { promise, reason });
});

使用 pino

const pino = require('pino');
const logger = pino({
  level: 'error',
  transport: {
    target: 'pino-pretty',
    options: { colorize: true }
  }
});

process.on('uncaughtException', (err) => {
  logger.error({ error: err });
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error({ promise, reason });
});

4. 将日志发送到远程服务器

如果你希望将日志发送到远程服务器进行集中管理,可以使用一些日志收集服务,比如 LogglyPapertrailELK Stack

使用 winston-loggly-bulk

const winston = require('winston');
const Loggly = require('winston-loggly-bulk').Loggly;

const logger = winston.createLogger({
  level: 'error',
  format: winston.format.json(),
  transports: [
    new Loggly({
      token: 'your-loggly-token',
      subdomain: 'your-loggly-subdomain',
      tag: 'your-app-tag'
    })
  ]
});

process.on('uncaughtException', (err) => {
  logger.error('There was an uncaught error', { error: err });
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error('Unhandled Rejection at:', { promise, reason });
});

5. 配置Ubuntu日志

如果你希望将Node.js应用的日志发送到Ubuntu的系统日志中,可以使用 syslogrsyslog

使用 syslog

const syslog = require('syslog');

const logger = syslog.createLogger({
  tag: 'your-app-tag',
  facility: syslog.LOG_USER
});

process.on('uncaughtException', (err) => {
  logger.error(`There was an uncaught error: ${err}`);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error(`Unhandled Rejection at: ${promise}, reason: ${reason}`);
});

使用 rsyslog

你可以配置 rsyslog 来接收Node.js应用的日志。

  1. 编辑 rsyslog 配置文件 /etc/rsyslog.conf/etc/rsyslog.d/50-default.conf,添加以下行:

    if $programname == 'your-app-name' then /var/log/your-app.log
    & stop
    
  2. 重启 rsyslog 服务:

    sudo systemctl restart rsyslog
    
  3. 在Node.js应用中使用 syslog 模块:

    const syslog = require('syslog');
    
    const logger = syslog.createLogger({
      tag: 'your-app-tag',
      facility: syslog.LOG_USER
    });
    
    process.on('uncaughtException', (err) => {
      logger.error(`There was an uncaught error: ${err}`);
      process.exit(1);
    });
    
    process.on('unhandledRejection', (reason, promise) => {
      logger.error(`Unhandled Rejection at: ${promise}, reason: ${reason}`);
    });
    

通过这些方法,你可以有效地捕获和记录Node.js应用中的异常,并将其发送到Ubuntu日志中,以便更好地监控和调试你的应用。

0
看了该问题的人还看了