在 Debian 上过滤 Node.js 日志,取决于日志写在哪里、用什么方式运行 Node.js。下面按常见场景给你一套实用做法。
node app.js
日志在终端,可直接用管道过滤:
node app.js | grep ERROR
node app.js | grep -i warn
如果你用:
systemctl start yourapp
日志由 journald 管理。
journalctl -u yourapp
journalctl -u yourapp | grep ERROR
journalctl -u yourapp -f | grep ERROR
journalctl -u yourapp --since "2024-01-01" --until "2024-01-02"
journalctl -u yourapp -p err
例如:
node app.js >> /var/log/node/app.log 2>&1
grep ERROR /var/log/node/app.log
tail -f /var/log/node/app.log | grep ERROR
grep -E "ERROR|WARN" /var/log/node/app.log
grep -v "healthcheck" /var/log/node/app.log
如 winston / pino:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
这样:
error.log 只有错误combined.log 全量很多框架支持:
LOG_LEVEL=error node app.js
jq 过滤 JSON 日志如果日志是 JSON:
cat app.log | jq 'select(.level=="error")'
/etc/logrotate.d/node-app
示例:
/var/log/node/*.log {
daily
rotate 7
compress
missingok
notifempty
}
| 场景 | 推荐方式 |
|---|---|
| 调试中 | node app.js | grep |
| systemd 服务 | journalctl -u |
| 生产环境 | 文件 + winston/pino |
| 实时排查 | tail -f | grep |
如果你愿意,可以告诉我:
我可以给你精确命令或配置。