在 Ubuntu 上分析 Node.js 日志,通常取决于你日志写入方式(console、文件、PM2、Docker、systemd 等)。下面按常见场景给你一套实用分析思路 + 命令。
node app.js
✅ 常见做法:
node app.js > logs/app.log 2>&1
如果你用 PM2 管理 Node.js:
pm2 logs
pm2 logs app-name
日志路径:
~/.pm2/logs/
常用:
pm2 logs --lines 100
pm2 flush # 清空日志
如果是 systemd 启动的 Node.js:
journalctl -u your-node-service
实时查看:
journalctl -u your-node-service -f
cat app.log
less app.log
tail -f app.log # 实时
grep -i error app.log
grep -i "exception" app.log
grep -i "failed" app.log
只看最近 200 行:
tail -n 200 app.log | grep ERROR
grep -c ERROR app.log
grep "2025-01-20" app.log
如果是 HTTP 日志:
grep "POST /api" app.log
grep "500" app.log
统计 500 错误:
grep " 500 " app.log | wc -l
如果 Node.js 使用 JSON 日志(如 pino、winston json):
cat app.log | jq '.level'
过滤 ERROR 级别:
cat app.log | jq 'select(.level=="error")'
日志中常见关键词:
heap out of memoryGCtimeoutETIMEDOUT配合:
dmesg | grep node
grep -i "crash" app.log
grep -i "signal" app.log
PM2:
pm2 list
pm2 show app-name
✅ 使用日志库:
✅ 日志至少包含:
{
"level": "error",
"time": "2025-01-20T10:00:00Z",
"message": "DB connection failed",
"stack": "..."
}
✅ 按级别分文件:
error.log
info.log
# 1. 看是否在运行
pm2 list
# 2. 看最新日志
pm2 logs --lines 100
# 3. 搜索错误
grep -i error ~/.pm2/logs/app-error.log
# 4. 看系统资源
top / htop
如果你愿意,可以告诉我:
我可以直接帮你针对你的环境写分析命令。