在 Ubuntu 上实时查看 Node.js 日志,常见做法取决于日志写在哪里。下面按常见场景给你最实用的方法。
如果你是这样启动的:
node app.js
日志直接输出在终端,不需要额外查看。
node app.js
pm2(强烈推荐)pm2 logs
只看某个应用:
pm2 logs app-name
只看 100 行并实时:
pm2 logs --lines 100
✅ 优点
nohup 启动nohup node app.js > app.log 2>&1 &
tail -f app.log
常用参数:
tail -f -n 100 app.log
systemd(服务器常用)服务文件示例:
[Service]
ExecStart=/usr/bin/node /opt/app/app.js
StandardOutput=append:/var/log/node/app.log
StandardError=append:/var/log/node/error.log
tail -f /var/log/node/app.log
或使用 journald:
journalctl -u your-service-name -f
docker logs -f container_id
只看最近 100 行:
docker logs -f --tail 100 container_id
const winston = require('winston');
const logger = winston.createLogger({
transports: [
new winston.transports.File({ filename: 'app.log' }),
new winston.transports.Console()
]
});
tail -f app.log
| 场景 | 命令 |
|---|---|
| 普通日志 | tail -f app.log |
| 最后 200 行 | tail -n 200 -f app.log |
| 搜索关键字 | `tail -f app.log |
| pm2 | pm2 logs |
| systemd | journalctl -u xxx -f |
| Docker | docker logs -f container |
✅ 生产环境
pm2 logs✅ 简单脚本
nohup + tail -f✅ 容器
docker logs -f如果你愿意,可以告诉我:
我可以给你一条最合适你环境的命令。