温馨提示×

linux中nodejs日志咋排查

小樊
38
2026-09-14 16:49:34
栏目: 编程语言

在 Linux 下排查 Node.js 日志,通常可以按下面几个层次来做:看日志在哪 → 看日志内容 → 动态排查 → 进程/资源 → 代码层


一、先确认日志在哪里

1. 应用自己打的日志

常见位置:

  • 项目目录下的 logs/
    ls -lh /path/to/project/logs
    
  • 代码里使用:
    • console.log / console.error
    • winston / pino / log4js

2. 使用 PM2 管理

pm2 logs
pm2 logs app_name
pm2 logs --lines 100

日志文件一般在:

~/.pm2/logs/

3. 使用 systemd(生产常见)

journalctl -u your-node-service
journalctl -u your-node-service -f
journalctl -u your-node-service --since "10 min ago"

二、实时查看日志(最常用)

1. tail 实时看

tail -f app.log
tail -n 200 app.log

2. 过滤关键字

tail -f app.log | grep ERROR
grep -i "timeout" app.log

三、Node.js 报错怎么看

1. 未捕获异常

典型日志:

Error: connect ECONNREFUSED
    at ...

重点看:

  • Error: 后面的信息
  • at 堆栈(定位文件和行号)

2. 内存溢出(OOM)

日志可能:

FATAL ERROR: Ineffective mark-compacts near heap limit

查看内存:

free -h
top

四、进程是否还活着

ps aux | grep node

pm2 status

端口是否监听:

netstat -tunlp | grep 3000
# 或
ss -tunlp | grep 3000

五、系统级排查(卡死/慢)

CPU

top
htop

文件描述符

lsof -p <pid>

磁盘

df -h
du -sh *

六、常见 Node.js 问题速查

问题 排查点
接口慢 日志耗时、DB 查询、CPU
进程挂掉 PM2 / systemd 日志
内存涨 heapdump、leak
请求失败 nginx / 反向代理日志

七、建议的日志规范(很重要)

  • 生产环境 不要用 console.log
  • 使用 winston / pino
  • 日志分级:info / warn / error
  • 输出到文件 + 可接 ELK / Loki

如果你愿意,可以把 具体的报错日志或启动方式(PM2 / Docker / systemd) 发出来,我可以帮你精确分析。

0