商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > Node.js应用在Ubuntu日志中的异常捕获

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

  发布于2026-05-21 阅读(0)

扫一扫,手机访问

在Ubuntu上部署Node.js应用,一个绕不开的核心议题就是异常处理。应用在线上跑起来,最怕的就是那些预料之外的错误悄无声息地发生,然后消失得无影无踪。把异常清晰地记录下来,尤其是整合到Ubuntu的系统日志体系中,这不仅是良好的开发习惯,更是生产环境稳定运行的基石。它能帮你快速定位问题、分析趋势,甚至实现自动化告警。

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

下面,我们就来梳理几种在Node.js中捕获异常并接入Ubuntu日志的主流方法,从基础到进阶,帮你构建更健壮的错误处理防线。

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

这是Node.js全局异常捕获的“最后一道防线”。当代码中有异常抛出却没有被任何try-catch捕获时,就会触发这个事件。不过要注意,捕获到此类异常后,应用状态可能已不可靠,通常建议记录日志后优雅退出。

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

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

在Promise成为主流的今天,未处理的Promise拒绝(Rejection)同样需要警惕。这个事件就是专门用来捕获那些既没有.catch()处理,也没有被await包裹的Promise错误。

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

3. 使用第三方日志库

直接使用console.error虽然简单,但在格式统一、日志分级、输出到文件等方面能力有限。这时,专业的日志库如winstonpino就能大显身手了。

使用 winston

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

pino以高性能著称,特别适合对日志吞吐量要求高的应用。它的JSON日志格式也便于后续的解析和分析。

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. 将日志发送到远程服务器

在分布式或微服务架构下,将各服务器的日志集中管理是更高效的做法。你可以借助LogglyPapertrail或自建的ELK Stack(Elasticsearch, Logstash, Kibana)来实现。

使用 winston-loggly-bulk

这里以winston集成Loggly为例,将错误日志直接发送到云端日志服务。

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的syslog体系。这样,你就可以使用journalctl等系统工具统一查看和管理所有日志。

使用 syslog 模块

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}`);
});

使用 rsyslog 进行高级配置

对于更复杂的路由和过滤需求,可以配置Ubuntu上更强大的rsyslog服务。

  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模块输出日志,此时日志会被rsyslog捕获并按上述规则处理:

    const syslog = require('syslog');
    const logger = syslog.createLogger({
      tag: 'your-app-tag',
      facility: syslog.LOG_USER
    });
    // ... 异常捕获和日志记录代码同上
    

综合运用以上几种方法,你就能为Node.js应用构建起从进程内捕获、到格式化记录、再到与Ubuntu系统日志生态无缝集成的完整异常监控链路。这不仅能提升调试效率,也为应用的长期稳定运行提供了坚实保障。

本文转载于:https://www.yisu.com/ask/94126126.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注