在 Ubuntu 上解析 Node.js 日志,通常取决于日志的来源和格式。下面按常见场景给你一套实用方案。
Node.js 日志常见位置:
node app.jspm2 logslogs/app.logjournalctl -u your-node-service/var/log/nginx/access.logtail -f /path/to/app.log
grep -i "error" app.log
grep -i "exception" app.log
grep "2024-01-21 10:" app.log
grep -c "Error" app.log
示例日志:
{"level":"error","time":"2024-01-21T10:00:00Z","msg":"DB timeout"}
解析方式:
cat app.log | jq 'select(.level=="error")'
安装 jq:
sudo apt install jq
const fs = require('fs');
const readline = require('readline');
const rl = readline.createInterface({
input: fs.createReadStream('/var/log/app.log')
});
rl.on('line', (line) => {
try {
const log = JSON.parse(line);
if (log.level === 'error') {
console.log(log.msg);
}
} catch (e) {
// 非 JSON 日志
}
});
pm2 logs
pm2 logs app --lines 100
pm2 flush # 清空日志
日志路径:
~/.pm2/logs/
如果 Node 是 systemd 服务:
journalctl -u node-app.service -f
journalctl -u node-app.service --since "2024-01-21 09:00"
我可以给你具体脚本或配置。