在 Linux 上导出 Node.js 日志,常见做法取决于日志是怎么产生的。下面按常见场景给你总结:
Node.js 默认日志一般打印到 stdout / stderr:
node app.js
node app.js > app.log 2>&1
>:标准输出2>&1:错误也写入nohup node app.js > app.log 2>&1 &
node app.js | tee app.log
pm2 logs --out app.out.log --err app.err.log
或查看已有日志:
pm2 logs
pm2 flush # 清空日志
日志默认位置:
~/.pm2/logs/
docker logs <container_id>
docker logs <container_id> > app.log 2>&1
docker logs -f <container_id> > app.log
使用 fs 或日志库(winston / pino):
const fs = require('fs');
console.log = (msg) => fs.appendFileSync('app.log', msg + '\n');
或使用 winston:
const winston = require('winston');
winston.add(new winston.transports.File({ filename: 'app.log' }));
如果 Node 是通过 systemd 启动:
journalctl -u node-app.service -f
导出:
journalctl -u node-app.service > node.log
journalctl --since "2024-01-01" --until "2024-01-02"
split -l 10000 app.log app_part_
如果你能告诉我:
我可以给你更精确的方案。