在 Linux 下解析 Node.js 日志,通常分为日志格式理解 → 收集方式 → 解析工具/方法 → 实战示例几个层面。下面按常见场景给你一个系统性的说明。
node app.js > app.log 2>&1
日志内容通常是:
info: server started on port 3000
error: DB connection failed
或 JSON 格式(推荐):
{"level":"error","time":"2024-01-01T10:00:00Z","msg":"db error","stack":"..."}
常见库:
winstonpino(性能最好,JSON 日志)bunyan示例(pino):
{"level":50,"time":1700000000000,"msg":"Unhandled error","pid":1234}
tail -f app.log
grep "error" app.log
awk '$1 >= "2024-01-01" && $1 <= "2024-01-02"' app.log
jqcat app.log | jq 'select(.level=="error")'
提取字段:
jq '.time, .msg' app.log
统计错误数量:
jq 'select(.level=="error")' app.log | wc -l
Node.js
↓
文件 / stdout
↓
Filebeat / Fluent Bit
↓
Elasticsearch / Loki
↓
Kibana / Grafana
如果你用 systemd 启动 Node.js:
journalctl -u node-app.service -f
导出为 JSON:
journalctl -u node-app.service -o json
const fs = require('fs');
const lines = fs.readFileSync('app.log', 'utf8').split('\n');
for (const line of lines) {
try {
const log = JSON.parse(line);
if (log.level === 'error') {
console.log(log.time, log.msg);
}
} catch {}
}
import json
with open('app.log') as f:
for line in f:
try:
log = json.loads(line)
if log['level'] == 'error':
print(log)
except:
pass
✅ 使用 JSON 日志
✅ 包含字段:
leveltimemsgpidtraceId(分布式追踪)❌ 不要只打纯文本日志(难解析)
Linux 下解析 Node.js 日志,最好用 JSON + jq / ELK / Loki,避免纯文本正则解析。
如果你愿意,可以:
winston / pino / pm2 / docker我可以给你针对性的解析命令或方案。