温馨提示×

怎么查看Ubuntu Nodejs日志

小樊
37
2026-07-10 05:07:57
栏目: 编程语言

在 Ubuntu 上查看 Node.js 日志 取决于你如何运行 Node.js 应用。下面按常见场景给你一个完整清单。


一、直接运行 Node.js(前台 / 终端)

如果你是这样启动的:

node app.js

✅ 日志会直接输出到终端(stdout / stderr)
✅ 无法“查看日志文件”,除非你重定向

查看方式

  • 直接在终端看
  • 或启动时重定向:
node app.js > app.log 2>&1

查看日志:

cat app.log
tail -f app.log

二、使用 PM2(最常见 ✅ 强烈推荐)

查看所有应用

pm2 list

查看实时日志

pm2 logs

查看指定应用日志

pm2 logs app-name

查看最近 100 行

pm2 logs --lines 100

日志文件路径

~/.pm2/logs/

例如:

~/.pm2/logs/app-name-out.log
~/.pm2/logs/app-name-error.log

三、使用 systemd(服务方式)

如果你是通过 systemd 管理 Node.js:

查看日志

sudo journalctl -u your-service-name

实时查看

sudo journalctl -u your-service-name -f

查看最近 100 行

sudo journalctl -u your-service-name -n 100

your-service-name.service 文件名


四、Docker 中运行 Node.js

查看容器日志

docker logs 容器ID或名称

实时查看

docker logs -f 容器ID

五、Nginx + Node.js(反向代理)

Node 本身日志看上面方法
Nginx 日志通常在:

/var/log/nginx/access.log
/var/log/nginx/error.log

查看:

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

六、Node.js 代码中的日志

console.log / console.error

console.log('info');
console.error('error');

使用日志库(推荐)

  • winston
  • pino

示例(winston):

const winston = require('winston');

const logger = winston.createLogger({
  transports: [
    new winston.transports.File({ filename: 'app.log' })
  ]
});

logger.info('hello');

查看:

tail -f app.log

七、快速排查建议 ✅

如果不知道日志在哪,先问自己:

  1. 怎么启动的?
    • node 直接运行 → 终端
    • pm2 → ~/.pm2/logs/
    • systemd → journalctl
  2. 有没有写文件?
    find / -name "*.log" 2>/dev/null | grep node
    

总结(最常用)

场景 命令
PM2 pm2 logs
systemd journalctl -u 服务名 -f
Docker docker logs -f 容器
普通运行 tail -f 日志文件

如果你愿意,可以告诉我:

  • ✅ 你是怎么启动 Node.js 的?
  • ✅ 使用的是 PM2 / Docker / systemd / 直接运行?
  • ✅ Ubuntu 版本

我可以给你精确到命令级别的排查方案。

0