溫馨提示×

如何通過Ubuntu Node.js日志監控應用狀態

小樊
41
2025-09-18 05:21:59
欄目: 編程語言

通過Ubuntu Node.js日志監控應用狀態的完整流程

一、前期準備:代碼層日志規范化

要實現有效的日志監控,首先需要在Node.js應用中規范日志的記錄方式。推薦使用成熟的日志庫(如winston、pino),避免直接使用console.log(無法滿足生產級需求)。
winston為例,配置步驟如下:

  1. 安裝依賴npm install winston
  2. 創建日志配置文件(如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;
    
  3. 在應用中使用日志
    const logger = require('./logger');
    logger.info('Application started on port 3000'); // 正常啟動日志
    logger.error('Database connection failed:', err); // 錯誤日志(包含堆棧信息)
    

關鍵點:通過日志級別區分事件嚴重性(如error用于故障、info用于常規狀態、debug用于調試),結構化日志(JSON格式)便于后續工具解析和可視化。

二、進程管理與實時日志監控

1. 使用PM2進行進程守護與日志管理

PM2是Node.js生產環境最常用的進程管理工具,支持日志聚合、實時流式查看、自動重啟(進程崩潰時自動恢復)等功能。

  • 安裝PM2npm 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會將日志保存在~/.pm2/logs/目錄下(如my-node-app-error.log、my-node-app-out.log
  • 其他常用命令
    • pm2 status:查看應用運行狀態(CPU、內存占用);
    • pm2 monit:實時監控應用資源使用情況(CPU、內存、日志輸出);
    • pm2 restart my-node-app:重啟應用(修改代碼后無需手動重啟)。
      PM2的優勢在于輕量、易用,適合中小型項目快速實現進程管理和日志監控。

2. 使用systemd實現系統級服務監控

若需要更嚴格的服務管理(如系統重啟后自動啟動應用),可將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跟蹤日志更新)
    systemd的優勢在于系統級集成,適合需要高可靠性的生產環境。

三、集中式日志管理與可視化

對于分布式系統或多節點應用,需要將日志集中存儲并可視化,便于統一分析和告警。常見方案有ELK Stack(Elasticsearch+Logstash+Kibana)和Prometheus+Grafana。

1. ELK Stack:日志收集、存儲與可視化

ELK是開源的日志管理解決方案,適合需要全文搜索、復雜查詢的場景。

  • 組件說明
    • Elasticsearch:分布式搜索引擎,存儲和索引日志;
    • Logstash:日志收集與處理管道(解析、過濾日志);
    • Kibana:可視化工具(創建儀表板、圖表)。
  • 配置步驟
    1. 安裝Elasticsearch
      sudo apt install elasticsearch
      sudo systemctl start elasticsearch
      sudo systemctl enable elasticsearch
      
    2. 安裝Logstash
      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 } # 控制臺輸出(調試用)
      }
      
    3. 安裝Kibana
      sudo apt install kibana
      sudo systemctl start kibana
      sudo systemctl enable kibana
      
      訪問http://<Ubuntu-IP>:5601,進入Kibana界面,創建索引模式(如nodejs-*),即可搜索和可視化日志。
  • 優勢:適合復雜日志分析(如查找特定錯誤、統計請求耗時),但配置較復雜。

2. Prometheus+Grafana:指標監控與可視化

若更關注應用性能指標(如請求次數、響應時間、內存占用),而非日志文本,可選擇Prometheus+Grafana方案。

  • 組件說明
    • Prometheus:時間序列數據庫,收集和存儲應用指標;
    • Grafana:可視化工具(創建儀表板,展示指標趨勢);
    • Node.js客戶端庫prom-client(用于暴露應用指標)。
  • 配置步驟
    1. 安裝Prometheus
      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端口
      
    2. 在Node.js應用中集成prom-client
      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'));
      
    3. 安裝Grafana
      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請求數”、“請求延遲”等面板)。
  • 優勢:適合實時性能監控,通過圖表直觀展示應用狀態,支持告警規則(如請求延遲超過閾值時發送郵件)。

四、告警配置:及時發現問題

監控的目的是及時發現問題,因此需要配置告警規則。以下是常見工具的告警配置方法:

1. PM2告警

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。

2. Prometheus告警

Prometheus通過Alertmanager組件實現告警。配置步驟如下:

  1. 安裝Alertmanager
    sudo apt install prometheus-alertmanager
    sudo systemctl start alertmanager
    sudo systemctl enable alertmanager
    
  2. 配置Prometheus告警規則(編輯/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)"
    
  3. 配置Alertmanager(編輯/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'
    
  4. 重啟服務sudo systemctl restart prometheus alertmanager
    當告警條件滿足時,Prometheus會將告警發送到Alertmanager,再由Alertmanager轉發到指定渠道(如郵件、Slack)。

五、最佳實踐總結

  1. 日志規范化:使用winston等庫,設置合理的日志級別(error、warn、info、debug),采用結構化格式(JSON),便于后續分析;
  2. 進程管理:使用PM2或systemd守護應用,確保進程崩潰時自動重啟,并集中管理日志;
  3. 集中式管理:對于生產環境,建議使用ELK或Prometheus+Grafana實現日志集中存儲和可視化,便于統一分析;
  4. 告警及時:配置合理的告警規則(如錯誤日志、高延遲),通過郵件、Slack等渠道及時通知運維人員;
  5. 定期審查:定期審查日志和告警規則,優化監控策略(如調整告警閾值),避免無效告警。

通過以上流程,可實現Ubuntu上Node.js應用狀態的全面監控,及時發現并解決問題,保障應用穩定運行。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女