温馨提示×

ubuntu nodejs日志如何导

小樊
46
2026-09-12 10:38:33
栏目: 编程语言

在 Ubuntu 上导出 Node.js 日志,通常有几种常见做法,取决于你的运行方式日志来源。下面按场景给你说明:


一、Node.js 控制台日志(stdout / stderr)

1️⃣ 直接运行 Node.js

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

2️⃣ 后台运行(nohup)

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

查看:

tail -f app.log

二、使用 PM2(最常见)

导出日志

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

或导出某个应用:

pm2 logs app --lines 1000 > app.log

查看日志位置

pm2 desc app

通常在:

~/.pm2/logs/

三、Systemd 服务方式

如果你的 Node.js 是 systemd 服务:

查看日志

journalctl -u your-node-service -f

导出日志到文件

journalctl -u your-node-service > node.log

指定时间:

journalctl -u your-node-service --since "2024-01-01" > node.log

四、Docker 中的 Node.js

查看日志

docker logs container_name

导出

docker logs container_name > node.log 2>&1

五、Node.js 应用内部写日志(推荐)

如果用 winston / pino

const fs = require('fs');
// 直接读日志文件导出即可

日志文件一般在:

logs/app.log

六、常用导出命令总结

# 实时查看
tail -f app.log

# 导出最近 1000 行
tail -n 1000 app.log > export.log

# 压缩
tar -czf node-logs.tar.gz app.log

如果你能告诉我:

  • ✅ Node.js 是怎么运行的(PM2 / systemd / docker / 直接跑)
  • ✅ 日志是 console 还是文件
  • ✅ 想导出到本地还是远程

我可以给你精确命令

0