温馨提示×

怎样读懂nodejs ubuntu日志

小樊
45
2026-09-03 10:54:59
栏目: 编程语言

在 Ubuntu 上“读懂 Node.js 日志”,一般可以从 日志来源 → 日志位置 → 日志内容 → 常见错误含义 → 排查方法 这个思路来。下面一步一步说。


一、Node.js 日志一般来自哪里?

Node.js 本身不会自动写系统日志,日志来源通常是:

  1. 应用自己打印的日志

    • console.log()
    • console.error()
    • 日志库(winston / pino / bunyan)
  2. 进程管理器日志

    • PM2
    • systemd(最常见)
    • forever
  3. Ubuntu 系统日志

    • /var/log/syslog
    • journalctl
  4. Web 服务器 / 反向代理

    • Nginx:/var/log/nginx/
    • Apache:/var/log/apache2/

二、常见日志位置(Ubuntu)

1️⃣ 用 systemd 运行的 Node.js(推荐)

如果你用 systemd 管理 Node 服务:

journalctl -u your-node-service.service -f

常用参数:

journalctl -u xxx.service -n 100   # 最近100行
journalctl -u xxx.service --since "10 min ago"

2️⃣ 用 PM2 运行

pm2 logs
pm2 logs app-name

日志文件位置:

~/.pm2/logs/

3️⃣ Node 自己输出到文件

例如:

node app.js > app.log 2>&1

查看:

tail -f app.log

4️⃣ Nginx + Node.js

Node 报错但请求失败,常看 Nginx:

tail -f /var/log/nginx/error.log
tail -f /var/log/nginx/access.log

三、怎么“读”Node.js 日志?

1️⃣ 看错误级别

  • INFO:正常信息
  • WARN:可能问题
  • ERROR:真实错误
  • UnhandledPromiseRejection:Promise 没 catch
  • TypeError / ReferenceError:代码问题

2️⃣ 典型 Node.js 错误解读

❌端口被占用

Error: listen EADDRINUSE: address already in use :::3000

✅ 解决:

lsof -i:3000
kill -9 PID

❌模块找不到

Error: Cannot find module 'express'

✅ 解决:

npm install

❌未捕获异常

UnhandledPromiseRejectionWarning

✅ 代码里加:

process.on('unhandledRejection', e => {
  console.error(e);
});

❌Nginx 502

connect() failed (111: Connection refused)

✅ Node 没启动 / 端口不对


四、推荐日志实践(更容易读懂)

✅ 使用日志库

const winston = require('winston');

✅ 区分环境

  • 开发:console
  • 生产:文件 + systemd

✅ 日志包含

  • 时间
  • 级别
  • 请求ID
  • 错误信息 + stack

五、快速排查流程(实战)

# 1. 看服务状态
systemctl status node-app

# 2. 看实时日志
journalctl -u node-app -f

# 3. 看端口
netstat -tlnp | grep node

# 4. 看 Nginx
tail -f /var/log/nginx/error.log

如果你愿意,可以把一段真实的 Node.js Ubuntu 日志贴出来,我可以帮你逐行解读并告诉你问题在哪、怎么修。

0