在 Node.js 中“过滤错误日志”通常有三种常见场景,下面我按使用频率从高到低给你讲,并附上可直接用的方案。
console + 条件判断最简单,但不够优雅:
try {
doSomething();
} catch (err) {
if (err.code !== 'ECONNRESET') {
console.error(err);
}
}
✅ 适合:临时屏蔽某些已知错误
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'); // 会输出
✅ 适合:生产环境、复杂过滤规则
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);
}
}
});
✅ 适合:高并发服务
如果你不能改代码(比如第三方库报错):
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 还是某个日志库?我可以直接帮你写一套完整可用的日志过滤方案。