在 Debian 上“过滤 Node.js 日志”通常分三种场景:命令行实时过滤、按文件/服务过滤、用工具长期管理日志。下面按常见用法说明。
grep 过滤如果你是前台运行 Node.js:
node app.js | grep ERROR
如果日志写到了文件:
tail -f /var/log/node/app.log | grep ERROR
多条件过滤:
grep -E "ERROR|WARN" app.log
忽略大小写:
grep -i error app.log
只看最近 100 行:
tail -n 100 app.log | grep ERROR
如果你用 systemd 管理 Node.js(如 /etc/systemd/system/node-app.service):
journalctl -u node-app -f
journalctl -u node-app | grep ERROR
journalctl -u node-app --since "2024-01-01 00:00:00"
journalctl -u node-app --since today
journalctl -u node-app -p err
winston / pino(Node.js 内部过滤)在代码里控制日志级别:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
transports: [
new winston.transports.File({ filename: 'app.log' })
]
});
只记录 error 及以上:
level: 'error'
logrotate(Debian 自带)防止日志过大:
sudo nano /etc/logrotate.d/node-app
示例:
/var/log/node/*.log {
daily
rotate 7
compress
missingok
notifempty
}
pm2 logs
pm2 logs --err
| 场景 | 推荐方式 |
|---|---|
| 本地调试 | `tail -f |
| 生产服务 | systemd + journalctl |
| 日志量大 | logrotate + winston/pino |
如果你能说明:
我可以给你更精确的过滤命令。