溫馨提示×

如何監控Ubuntu JS日志

小樊
43
2025-09-24 16:20:57
欄目: 編程語言

監控Ubuntu上JavaScript(Node.js)日志的方法

一、基礎實時監控工具

1. 使用tail命令實時查看日志

tail -f是Linux系統最常用的實時日志查看工具,可直接跟蹤日志文件的新增內容。例如,若應用日志保存在/var/log/my-js-app.log,執行以下命令即可實時查看:
tail -f /var/log/my-js-app.log
Ctrl+C可停止監控。此方法適合快速查看實時日志流,無需額外配置。

2. 使用journalctl查看系統日志

若JavaScript應用通過systemd以服務形式運行(如node-app.service),可使用journalctl查看其日志。常用命令:

  • 查看所有日志:journalctl
  • 查看特定服務日志:journalctl -u your-js-service-name
  • 實時查看服務日志:journalctl -u your-js-service-name -f
  • 篩選錯誤日志:journalctl -p err -u your-js-service-name
    此方法適合集中管理系統日志,無需直接訪問應用日志文件。

二、應用層日志記錄配置

1. 使用Winston日志庫(推薦)

Winston是Node.js生態中最流行的日志庫,支持多傳輸(文件、控制臺、數據庫等)、多級別(info/warn/error)、結構化日志。安裝與配置示例:

npm install winston

配置文件(如logger.js):

const winston = require('winston');
const logger = winston.createLogger({
  level: 'info', // 日志級別(info及以上會記錄)
  format: 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('Server started on port 3000');
logger.error('Database connection failed');

Winston的優勢在于靈活的日志分級結構化輸出,便于后續通過ELK等工具分析。

2. 使用PM2進程管理器

PM2是Node.js生產環境的常用進程管理工具,內置日志管理、進程守護、負載均衡功能。安裝與使用:

npm install pm2 -g

啟動應用并記錄日志:

pm2 start app.js --name "my-js-app" --log /var/log/my-js-app.log

查看實時日志:

pm2 logs my-js-app

日志輪轉配置(避免日志過大):

pm2 set pm2-logrotate:max_size 10M # 單個日志文件最大10MB
pm2 set pm2-logrotate:retain 7    # 保留最近7天日志

PM2適合生產環境,簡化了日志管理與進程守護流程。

三、集中式日志管理方案

1. ELK Stack(Elasticsearch+Logstash+Kibana)

ELK是開源的日志集中化管理與分析平臺,適合大規模應用。搭建步驟:

  • 安裝Elasticsearch
    sudo apt-get install elasticsearch
    sudo systemctl start elasticsearch
    
  • 安裝Logstash
    sudo apt-get install logstash
    
    配置Logstash收集Node.js日志(/etc/logstash/conf.d/nodejs.conf):
    input {
      file {
        path => "/var/log/my-js-app.log"
        start_position => "beginning"
      }
    }
    output {
      elasticsearch {
        hosts => ["localhost:9200"]
        index => "nodejs-logs-%{+YYYY.MM.dd}"
      }
    }
    
  • 安裝Kibana
    sudo apt-get install kibana
    sudo systemctl start kibana
    
    訪問http://your-server-ip:5601,通過Kibana創建儀表盤,可視化日志數據(如錯誤率、請求頻率)。

2. Prometheus+Grafana(監控與可視化)

若需監控應用性能指標(如請求延遲、內存使用),可結合Prometheus(指標收集)與Grafana(可視化)。步驟:

  • 安裝Prometheus客戶端庫
    npm install prom-client
    
    在應用中定義指標(如http_requests_total):
    const promClient = require('prom-client');
    const httpRequestCounter = new promClient.Counter({
      name: 'http_requests_total',
      help: 'Total HTTP requests',
      labelNames: ['method', 'path']
    });
    app.use((req, res, next) => {
      httpRequestCounter.inc({ method: req.method, path: req.path });
      next();
    });
    
  • 配置Prometheus
    編輯/etc/prometheus/prometheus.yml,添加Node.js應用作為目標:
    scrape_configs:
      - job_name: 'nodejs'
        static_configs:
          - targets: ['localhost:9090'] # 應用需暴露Prometheus metrics接口
    
  • 配置Grafana
    添加Prometheus為數據源,導入Node.js監控儀表盤(如ID:1860),實時查看性能指標。

四、日志輪轉管理

為避免日志文件過大占用磁盤空間,需配置日志輪轉。使用logrotate工具(Ubuntu自帶):

  • 創建配置文件(/etc/logrotate.d/my-js-app):
    /var/log/my-js-app.log {
      daily       # 每天輪轉
      missingok   # 文件不存在時不報錯
      rotate 7    # 保留最近7份
      compress    # 壓縮舊日志(.gz格式)
      notifempty  # 空日志不輪轉
      create 640 root adm # 新日志權限
    }
    
  • 測試配置:
    sudo logrotate -f /etc/logrotate.d/my-js-app
    

此方法可自動化日志管理,減少人工干預。

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