温馨提示×

如何解析debian nodejs日志

小樊
46
2026-09-22 10:58:36
栏目: 编程语言

在 Debian 系统上解析 Node.js 日志,通常取决于日志是如何产生的(原生 console、PM2、systemd、Docker、日志库等)。下面按常见场景逐步说明。


一、先确认日志在哪里

1. 使用 systemd 管理的 Node.js 服务

如果 Node.js 是通过 systemd 启动的(常见于 Debian 服务器):

journalctl -u your-node-service.service

实时查看:

journalctl -u your-node-service.service -f

按时间筛选:

journalctl -u your-node-service.service --since "2024-01-01" --until "2024-01-02"

导出日志:

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

2. 使用 PM2 管理的 Node.js

查看日志路径:

pm2 logs
pm2 logs app-name

日志文件位置:

~/.pm2/logs/

解析错误日志:

pm2 logs --err

3. 原生 console.log / 文件日志

常见文件位置:

/var/log/node/
/home/user/app/logs/

查看:

tail -f app.log
less app.log

二、Node.js 日志的常见格式

1. 简单日志(console.log)

2024-01-01T12:00:00.000Z INFO Server started
2024-01-01T12:00:01.000Z ERROR DB connection failed

2. JSON 日志(推荐)

{"level":"error","time":"2024-01-01T12:00:01Z","msg":"DB error","stack":"..."}

常用库:

  • pino
  • winston
  • bunyan

三、基础日志解析方法

1. 按关键字过滤

grep ERROR node.log
grep -i "timeout" node.log

2. 统计错误数量

grep -c ERROR node.log

3. 查看最近 100 行

tail -n 100 node.log

4. 实时跟踪

tail -f node.log

四、解析 JSON 日志(进阶)

使用 jq

cat node.log | jq '.'

只看错误:

cat node.log | jq 'select(.level=="error")'

提取字段:

cat node.log | jq '.msg'

五、结合日志分析工具(推荐)

1. 本地工具

  • less(搜索 /ERROR
  • grep / awk / sed
  • jq(JSON)

2. 集中式日志

  • ELK(Elasticsearch + Logstash + Kibana)
  • Grafana Loki
  • Fluent Bit

六、Node.js 日志最佳实践(Debian 环境)

✅ 使用 JSON 日志
✅ 使用 pinowinston
✅ 输出到 stdout(让 systemd / Docker 收集)
✅ 设置日志级别(debug / info / error)
❌ 不要手动写文件日志(除非必要)


七、示例:systemd + Node.js 标准输出

/etc/systemd/system/node-app.service

[Service]
ExecStart=/usr/bin/node /opt/app/index.js
Restart=always
StandardOutput=journal
StandardError=journal

如果你能提供:

  • Node.js 启动方式(systemd / pm2 / docker)
  • 日志示例格式
  • 想解决的问题(性能 / 报错 / 安全)

我可以给你更具体的解析命令或脚本

0