在 Ubuntu 上导出 Node.js 日志,常见做法取决于日志是写到哪里的。下面按最常见的几种场景给你完整说明。
console.log / console.error 输出(最常见)Node.js 默认输出到 标准输出 stdout / 标准错误 stderr,在 Ubuntu 上通常可以通过:
node app.js > app.log 2>&1
说明:
>:标准输出2>&1:错误也写入同一文件✅ 导出到 app.log
nohup node app.js > app.log 2>&1 &
查看日志:
tail -f app.log
如果你用 PM2,日志管理非常方便。
pm2 logs
或查看指定应用:
pm2 logs app-name
PM2 日志默认在:
~/.pm2/logs/
例如:
app-name-out.log
app-name-error.log
导出:
cp ~/.pm2/logs/app-name-out.log /backup/app.log
pm2 logs app-name --lines 1000 > export.log
如果你的代码里用了日志库,比如:
const winston = require('winston');
const logger = winston.createLogger({
transports: [
new winston.transports.File({ filename: 'app.log' })
]
});
cat app.log
cp app.log /backup/
查看实时日志:
tail -f app.log
如果是通过 systemd 启动的 Node.js:
journalctl -u your-node-service.service
journalctl -u your-node-service.service > node-logs.log
实时查看:
journalctl -u your-node-service.service -f
docker logs container_id > node.log 2>&1
实时:
docker logs -f container_id
| 需求 | 命令 |
|---|---|
| 实时查看 | tail -f app.log |
| 导出最近 1000 行 | tail -n 1000 app.log > export.log |
| 搜索错误 | grep -i error app.log |
| 按时间导出 | sed -n '/2025-01-01/,/2025-01-02/p' app.log |
✅ 生产环境:
✅ 避免:
console.log如果你愿意,可以告诉我:
console.log 还是 winston?我可以给你针对你环境的精确导出方案。