在 Linux 上排查 Node.js 日志和错误,一般按「看日志 → 看进程 → 看系统 → 看代码」的顺序来。下面给你一套实用排查思路。
常见位置:
./logs/
./log/
winston、pino、log4js 等框架查看:
cat app.log
tail -f app.log
less app.log
pm2 logs
pm2 logs app-name
pm2 logs --err # 只看错误
pm2 describe app-name
如果是 systemctl 启动:
journalctl -u your-node-service -f
journalctl -u your-node-service --since "10 min ago"
docker logs -f container_id
docker logs --tail 100 container_id
看错误栈:
node app.js
常见原因:
lsof -i:3000
netstat -tunlp | grep 3000
日志中常见:
TypeError: Cannot read property 'x' of undefined
Error: connect ECONNREFUSED
UnhandledPromiseRejectionWarning
建议:
process.on('uncaughtException', e => {
console.error('uncaught', e);
});
process.on('unhandledRejection', e => {
console.error('unhandledRejection', e);
});
日志:
FATAL ERROR: Ineffective mark-compacts
JavaScript heap out of memory
排查:
node --max-old-space-size=1024 app.js
长期解决:
heapdump 分析top
# 找到 node 进程 PID
pidstat -p PID 1
Node 层:
node --prof app.js
node --prof-process isolate-*.log
# 实时看日志
tail -f app.log
# 看报错关键字
grep -i error app.log
grep -i exception app.log
# 看进程
ps aux | grep node
pm2 list
# 看端口
lsof -i:3000
# 看系统资源
top
free -h
df -h
info / warn / errorconsole.log如果你愿意,可以把具体报错日志或启动方式(PM2 / Docker / systemd)发出来,我可以直接帮你定位。