debian

如何通过日志监控 Debian Node.js 运行状态

小樊
37
2025-10-12 00:15:42
栏目: 编程语言

要通过日志监控 Debian 上的 Node.js 应用程序运行状态,您可以遵循以下步骤:

1. 配置日志记录

首先,确保您的 Node.js 应用程序配置了适当的日志记录机制。常用的日志库包括 winstonmorganpino。以下是一个使用 winston 的示例配置:

const winston = require('winston');

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

if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple()
  }));
}

2. 使用 pm2 进行进程管理

pm2 是一个流行的 Node.js 进程管理器,它可以自动重启应用程序、监控日志等。首先,安装 pm2

sudo npm install pm2 -g

然后,使用 pm2 启动您的 Node.js 应用程序:

pm2 start app.js --name my-app

3. 监控日志

您可以使用 pm2 的日志管理功能来监控应用程序的日志。以下是一些常用的命令:

4. 使用 tail 命令实时监控日志文件

如果您更喜欢直接查看日志文件,可以使用 tail 命令:

tail -f /path/to/your/logs/combined.log

5. 设置日志轮转

为了避免日志文件过大,您可以设置日志轮转。pm2 支持自动日志轮转。您可以在启动应用程序时配置日志轮转:

pm2 start app.js --name my-app --log-date-format "YYYY-MM-DD HH:mm Z"

6. 使用监控工具

对于更高级的监控需求,您可以使用 Prometheus 和 Grafana 等工具来收集和可视化日志数据。

安装 Prometheus 和 Grafana

首先,安装 Prometheus 和 Grafana:

sudo apt-get update
sudo apt-get install prometheus grafana

配置 Prometheus 抓取 Node.js 应用程序的指标

编辑 Prometheus 的配置文件 /etc/prometheus/prometheus.yml,添加您的 Node.js 应用程序的抓取配置:

scrape_configs:
  - job_name: 'node'
    static_configs:
      - targets: ['localhost:9090']

启动 Prometheus 和 Grafana

启动 Prometheus 和 Grafana 服务:

sudo systemctl start prometheus
sudo systemctl start grafana-server

配置 Grafana 数据源

在 Grafana 中配置 Prometheus 作为数据源,并创建仪表盘来可视化您的日志数据。

通过以上步骤,您可以有效地监控 Debian 上的 Node.js 应用程序运行状态。

0
看了该问题的人还看了