温馨提示×

怎样过滤nodejs错误日志

小樊
42
2026-09-18 14:59:46
栏目: 编程语言

在 Node.js 中“过滤错误日志”通常有三种常见场景,下面我按使用频率从高到低给你讲,并附上可直接用的方案。


一、在代码里过滤(最常用)

1️⃣ 用 console + 条件判断

最简单,但不够优雅:

try {
  doSomething();
} catch (err) {
  if (err.code !== 'ECONNRESET') {
    console.error(err);
  }
}

✅ 适合:临时屏蔽某些已知错误


2️⃣ 使用日志库(推荐)

✅ Winston(最流行)

npm install winston
const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.printf(info => {
          if (info.level === 'error' && info.message.includes('ECONNRESET')) {
            return ''; // 过滤掉
          }
          return `${info.level}: ${info.message}`;
        })
      )
    })
  ]
});

logger.error('ECONNRESET xxx'); // 不会输出
logger.error('real error');     // 会输出

✅ 适合:生产环境、复杂过滤规则


✅ Pino(高性能)

npm install pino
const pino = require('pino');

const logger = pino({
  level: 'info',
  hooks: {
    logMethod(args, method) {
      if (args[0] && args[0].includes('ECONNRESET')) return;
      method.apply(this, args);
    }
  }
});

✅ 适合:高并发服务


二、在进程层面过滤(stdout / stderr)

如果你不能改代码(比如第三方库报错):

Linux / Mac

node app.js 2>&1 | grep -v "ECONNRESET"

或只保留 error:

node app.js 2>&1 | grep "Error"

✅ 适合:临时排查问题


三、在运行时捕获并统一过滤

全局错误拦截

process.on('uncaughtException', err => {
  if (err.code === 'ECONNRESET') return;
  console.error(err);
});

process.on('unhandledRejection', err => {
  if (err.code === 'ECONNRESET') return;
  console.error(err);
});

⚠️ 注意:
uncaughtException 不建议吞掉错误,除非你非常清楚后果


四、按“错误类型”过滤的常见方式

过滤维度 示例
错误码 err.code === 'ENOENT'
错误消息 err.message.includes('timeout')
错误类型 err instanceof TypeError
来源模块 err.stack.includes('mysql')

推荐方案总结

开发console + 条件
生产Winston / Pino
临时排查grep
不要:无脑吞 uncaughtException


如果你愿意,可以告诉我:

  • 用的是 console 还是某个日志库?
  • 想过滤“哪种错误”?
  • 是开发环境还是生产环境?

我可以直接帮你写一套完整可用的日志过滤方案

0