通過Ubuntu Node.js日志監控應用狀態的完整流程
要實現有效的日志監控,首先需要在Node.js應用中規范日志的記錄方式。推薦使用成熟的日志庫(如winston
、pino
),避免直接使用console.log
(無法滿足生產級需求)。
以winston
為例,配置步驟如下:
npm install winston
logger.js
),設置日志級別、格式和傳輸目的地:const winston = require('winston');
const logger = winston.createLogger({
level: 'info', // 日志級別(從低到高:error < warn < info < debug)
format: winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), // 添加時間戳
winston.format.json() // 結構化日志(便于后續分析)
),
transports: [
new winston.transports.Console(), // 輸出到控制臺(開發環境)
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }), // 錯誤日志單獨存儲
new winston.transports.File({ filename: 'logs/combined.log' }) // 所有日志匯總
]
});
module.exports = logger;
const logger = require('./logger');
logger.info('Application started on port 3000'); // 正常啟動日志
logger.error('Database connection failed:', err); // 錯誤日志(包含堆棧信息)
關鍵點:通過日志級別區分事件嚴重性(如error
用于故障、info
用于常規狀態、debug
用于調試),結構化日志(JSON格式)便于后續工具解析和可視化。
PM2是Node.js生產環境最常用的進程管理工具,支持日志聚合、實時流式查看、自動重啟(進程崩潰時自動恢復)等功能。
npm install pm2 -g
pm2 start app.js --name "my-node-app"
(--name
指定應用名稱,便于后續管理)pm2 logs my-node-app
(按Ctrl+C
退出;添加-f
參數可跟蹤日志更新,如pm2 logs -f my-node-app
)~/.pm2/logs/
目錄下(如my-node-app-error.log
、my-node-app-out.log
)pm2 status
:查看應用運行狀態(CPU、內存占用);pm2 monit
:實時監控應用資源使用情況(CPU、內存、日志輸出);pm2 restart my-node-app
:重啟應用(修改代碼后無需手動重啟)。若需要更嚴格的服務管理(如系統重啟后自動啟動應用),可將Node.js應用配置為systemd服務。
sudo vim /etc/systemd/system/my-node-app.service
,內容如下:[Unit]
Description=My Node.js Application
After=network.target # 依賴網絡服務啟動
[Service]
ExecStart=/usr/bin/node /path/to/your/app.js # 應用入口文件路徑
Restart=always # 崩潰時自動重啟
User=ubuntu # 運行用戶(建議使用非root)
Environment=NODE_ENV=production # 設置環境變量
WorkingDirectory=/path/to/your/app # 應用根目錄
[Install]
WantedBy=multi-user.target # 多用戶模式下啟動
sudo systemctl daemon-reload # 重新加載systemd配置
sudo systemctl start my-node-app # 啟動服務
sudo systemctl enable my-node-app # 開機自啟
sudo systemctl status my-node-app
(顯示應用運行狀態、日志輸出)journalctl -u my-node-app -f
(-u
指定服務名稱,-f
跟蹤日志更新)對于分布式系統或多節點應用,需要將日志集中存儲并可視化,便于統一分析和告警。常見方案有ELK Stack(Elasticsearch+Logstash+Kibana)和Prometheus+Grafana。
ELK是開源的日志管理解決方案,適合需要全文搜索、復雜查詢的場景。
sudo apt install elasticsearch
sudo systemctl start elasticsearch
sudo systemctl enable elasticsearch
sudo apt install logstash
創建Logstash配置文件(如/etc/logstash/conf.d/nodejs.conf
),用于接收Node.js日志:input {
file {
path => "/path/to/your/logs/combined.log" # Node.js日志文件路徑
start_position => "beginning" # 從文件開頭讀?。ㄊ状闻渲脮r)
sincedb_path => "/dev/null" # 忽略sincedb文件(測試用)
}
}
filter {
grok { match => { "message" => "%{TIMESTAMP_ISO8601:timestamp} %{LOGLEVEL:loglevel} %{GREEDYDATA:logmessage}" } } # 解析日志格式
date { match => [ "timestamp", "ISO8601" ] } # 轉換時間格式
}
output {
elasticsearch { hosts => ["localhost:9200"] } # 發送到Elasticsearch
stdout { codec => rubydebug } # 控制臺輸出(調試用)
}
sudo apt install kibana
sudo systemctl start kibana
sudo systemctl enable kibana
訪問http://<Ubuntu-IP>:5601
,進入Kibana界面,創建索引模式(如nodejs-*
),即可搜索和可視化日志。若更關注應用性能指標(如請求次數、響應時間、內存占用),而非日志文本,可選擇Prometheus+Grafana方案。
prom-client
(用于暴露應用指標)。sudo apt install prometheus
sudo systemctl start prometheus
sudo systemctl enable prometheus
修改/etc/prometheus/prometheus.yml
,添加Node.js應用的監控目標:scrape_configs:
- job_name: 'nodejs'
static_configs:
- targets: ['localhost:9090'] # Node.js應用的metrics端口
npm install prom-client
創建指標收集代碼(如metrics.js
):const client = require('prom-client');
const collectDefaultMetrics = client.collectDefaultMetrics; // 收集默認指標(CPU、內存)
collectDefaultMetrics({ timeout: 5000 });
// 自定義指標:HTTP請求數
const httpRequestCounter = new client.Counter({
name: 'http_requests_total',
help: 'Total number of HTTP requests',
labelNames: ['method', 'route', 'status']
});
// 自定義指標:請求延遲
const httpRequestDuration = new client.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route', 'status'],
buckets: [0.1, 0.5, 1, 2, 5] // 桶邊界(秒)
});
module.exports = { httpRequestCounter, httpRequestDuration };
在Express應用中使用指標中間件:const express = require('express');
const { httpRequestCounter, httpRequestDuration } = require('./metrics');
const app = express();
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = (Date.now() - start) / 1000; // 計算請求耗時(秒)
httpRequestCounter.inc({ method: req.method, route: req.route?.path || req.path, status: res.statusCode });
httpRequestDuration.observe({ method: req.method, route: req.route?.path || req.path, status: res.statusCode }, duration);
});
next();
});
app.get('/', (req, res) => res.send('Hello World'));
app.listen(3000, () => console.log('Server started on port 3000'));
sudo apt install grafana
sudo systemctl start grafana-server
sudo systemctl enable grafana-server
訪問http://<Ubuntu-IP>:3000
(默認賬號admin
,密碼admin
),添加Prometheus數據源(URL為http://localhost:9090
),然后創建儀表板(如添加“HTTP請求數”、“請求延遲”等面板)。監控的目的是及時發現問題,因此需要配置告警規則。以下是常見工具的告警配置方法:
PM2內置了簡單的告警功能,可通過pm2 install
安裝插件(如pm2-webshell
、pm2-logrotate
),或集成第三方告警服務(如Slack、Email)。
示例:使用pm2-logrotate
實現日志輪轉(避免日志文件過大):
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M # 單個日志文件最大10MB
pm2 set pm2-logrotate:retain 7 # 保留最近7天日志
更復雜的告警(如錯誤日志觸發郵件),可使用pm2-plus
(PM2的商業版)或集成Zapier
。
Prometheus通過Alertmanager組件實現告警。配置步驟如下:
sudo apt install prometheus-alertmanager
sudo systemctl start alertmanager
sudo systemctl enable alertmanager
/etc/prometheus/prometheus.yml
):rule_files:
- "/etc/prometheus/alert.rules"
創建/etc/prometheus/alert.rules
文件,定義告警規則(如請求延遲超過2秒):groups:
- name: nodejs_alerts
rules:
- alert: HighRequestLatency
expr: histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[1m])) by (le)) > 2
for: 5m # 持續5分鐘觸發告警
labels:
severity: warning
annotations:
summary: "High request latency on {{ $labels.instance }}"
description: "95th percentile request latency is {{ $value }}s (threshold: 2s)"
/etc/alertmanager/alertmanager.yml
):route:
receiver: 'email'
receivers:
- name: 'email'
email_configs:
- to: 'your-email@example.com'
from: 'alertmanager@example.com'
smarthost: 'smtp.example.com:587'
auth_username: 'your-username'
auth_password: 'your-password'
sudo systemctl restart prometheus alertmanager
winston
等庫,設置合理的日志級別(error
、warn
、info
、debug
),采用結構化格式(JSON),便于后續分析;通過以上流程,可實現Ubuntu上Node.js應用狀態的全面監控,及時發現并解決問題,保障應用穩定運行。