温馨提示×

linux nodejs日志怎么导出

小樊
44
2026-09-17 18:20:01
栏目: 编程语言

在 Linux 上导出 Node.js 日志,常见做法取决于日志是怎么产生的。下面按常见场景给你总结:


一、Node.js 直接输出到控制台(最常见)

Node.js 默认日志一般打印到 stdout / stderr:

node app.js

1. 重定向到文件(最简单)

node app.js > app.log 2>&1
  • >:标准输出
  • 2>&1:错误也写入

2. 后台运行并导出日志

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

3. 实时查看并保存

node app.js | tee app.log

二、使用 PM2 管理 Node.js(推荐)

导出日志

pm2 logs --out app.out.log --err app.err.log

或查看已有日志:

pm2 logs
pm2 flush   # 清空日志

日志默认位置:

~/.pm2/logs/

三、Docker 中的 Node.js 日志

查看日志

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' }));

五、系统级日志(journalctl)

如果 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_

如果你能告诉我:

  • 是用 pm2 / docker / 裸 node
  • 日志是 console 还是文件
  • 想要 实时 / 历史 / 自动轮转

我可以给你更精确的方案。

0 踩