溫馨提示×

Debian Node.js 日志配置技巧

小樊
34
2025-08-23 15:13:22
欄目: 編程語言

以下是Debian下Node.js日志配置的核心技巧:

  1. 選擇日志庫:推薦Winston(支持多傳輸、格式化)、Pino(高性能JSON格式)、Log4js(靈活配置)。
  2. 控制日志級別:通過庫配置(如level: 'info')或環境變量(如LOG_LEVEL=debug)動態調整,生產環境建議僅保留error/warn。
  3. 日志輪轉與歸檔:使用winston-daily-rotate-file插件按天/大小分割日志,支持壓縮和保留天數配置。
  4. 集中式管理:集成ELK Stack(Elasticsearch+Logstash+Kibana)或Graylog,實現日志聚合與分析。
  5. 性能優化:啟用異步日志寫入(多數庫默認支持),避免阻塞主線程。
  6. 格式化輸出:自定義JSON格式(含時間戳、級別、消息),或使用庫自帶格式化器(如Winston的printf)。
  7. 環境適配:開發環境輸出詳細日志,生產環境通過配置文件或PM2限制輸出級別。

示例代碼(Winston配置):

const winston = require('winston');
const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  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: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

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