温馨提示×

如何监控Debian Nodejs日志

小樊
37
2026-07-13 03:51:08
栏目: 编程语言

在 Debian 上监控 Node.js 日志,常见做法取决于日志输出方式(stdout / 文件 / 日志库)以及运行方式(systemd、PM2、Docker 等)。下面按常见场景给你一套实用方案。


一、最基础:直接查看日志

1️⃣ Node.js 直接输出到 stdout

node app.js

查看:

tail -f nohup.out
# 或
journalctl -f

二、使用 systemd(推荐,生产环境)

1️⃣ 创建 systemd 服务

# /etc/systemd/system/nodeapp.service
[Unit]
Description=Node.js App
After=network.target

[Service]
User=node
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/node index.js
Restart=always
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

2️⃣ 启动并查看日志

sudo systemctl daemon-reload
sudo systemctl start nodeapp
sudo systemctl status nodeapp

3️⃣ 实时查看日志

journalctl -u nodeapp -f

4️⃣ 查看历史日志

journalctl -u nodeapp --since "2025-01-01" --until "2025-01-02"

优点

  • 自动重启
  • 日志集中管理
  • 支持时间查询

三、使用 PM2(Node.js 专用)

1️⃣ 安装 PM2

npm install -g pm2

2️⃣ 启动应用

pm2 start index.js --name myapp

3️⃣ 查看日志

pm2 logs myapp
pm2 logs myapp --lines 100

4️⃣ 实时监听

pm2 logs myapp --lines 0

5️⃣ 日志文件位置

~/.pm2/logs/

优点

  • 自动重启
  • 内置日志管理
  • 适合 Node.js 项目

四、日志写入文件(传统方式)

1️⃣ Node.js 代码示例

const fs = require('fs');
const logStream = fs.createWriteStream('/var/log/node/app.log', { flags: 'a' });

console.log = (msg) => {
  logStream.write(`${new Date().toISOString()} ${msg}\n`);
};

2️⃣ 查看日志

tail -f /var/log/node/app.log

⚠️ 注意:

  • 需要手动做日志切割
  • 不适合大规模系统

五、使用专业日志库(强烈推荐)

常用库

  • Winston
  • Pino(性能最好)

Winston 示例

const winston = require('winston');

const logger = winston.createLogger({
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

logger.info('服务启动');

查看

tail -f combined.log

✅ 支持:

  • 日志级别
  • 多输出(文件 + console)
  • 格式化

六、集中式日志监控(进阶)

常见组合

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

适合:

  • 多台服务器
  • 微服务
  • 生产环境

七、推荐方案总结

场景 推荐方式
本地开发 console.log + tail -f
单台服务器 systemd / PM2
生产环境 systemd + Winston
大规模 ELK / Loki

如果你愿意,可以告诉我:

  • ✅ Node.js 运行方式(systemd / PM2 / Docker)
  • ✅ Debian 版本
  • ✅ 是否生产环境

我可以帮你定制一套完整监控方案

0