插件窝 干货文章 Linux环境下Node.js日志优化方法

Linux环境下Node.js日志优化方法

日志 const javascript error 312    来源:    2025-05-04

Linux环境下Node.js日志优化方法

一、日志级别优化

  1. 合理设置日志级别

    const winston = require('winston');
    
    const logger = winston.createLogger({
     level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
     transports: [new winston.transports.Console()]
    });
    
  2. 使用环境变量控制日志级别

    # 生产环境
    export LOG_LEVEL=warn
    
    # 开发环境
    export LOG_LEVEL=debug
    

二、日志格式化优化

  1. 结构化日志(JSON格式)

    const { createLogger, format, transports } = require('winston');
    
    const logger = createLogger({
     format: format.json(),
     transports: [new transports.Console()]
    });
    
  2. 添加时间戳和上下文

    format: format.combine(
     format.timestamp(),
     format.metadata({ fillExcept: ['message', 'level', 'timestamp'] })
    )
    

三、日志轮转与存储

  1. 使用winston-daily-rotate-file

    const DailyRotateFile = require('winston-daily-rotate-file');
    
    logger.add(new DailyRotateFile({
     filename: 'application-%DATE%.log',
     datePattern: 'YYYY-MM-DD',
     zippedArchive: true,
     maxSize: '20m',
     maxFiles: '14d'
    }));
    
  2. Linux logrotate配置

    # /etc/logrotate.d/nodejs-app
    /var/log/nodejs/app.log {
       daily
       missingok
       rotate 30
       compress
       delaycompress
       notifempty
       copytruncate
    }
    

四、性能优化

  1. 异步日志记录

    const { AsyncLocalStorage } = require('async_hooks');
    const asyncLocalStorage = new AsyncLocalStorage();
    
    // 在中间件中设置上下文
    app.use((req, res, next) => {
     asyncLocalStorage.run(new Map(), () => {
       asyncLocalStorage.getStore().set('requestId', uuid.v4());
       next();
     });
    });
    
  2. 批量写入日志

    const { Writable } = require('stream');
    
    class BatchStream extends Writable {
     constructor(options) {
       super(options);
       this.batch = [];
       this.batchSize = options.batchSize || 10;
     }
    
     _write(chunk, encoding, callback) {
       this.batch.push(chunk);
       if (this.batch.length >= this.batchSize) {
         this._flushBatch();
       }
       callback();
     }
    }
    

五、高级日志分析

  1. ELK Stack集成

    • 配置Logstash收集Node.js日志
    • 使用Filebeat将日志发送到Logstash
    • 在Kibana中创建可视化仪表板
  2. 错误追踪集成

    const { Sentry } = require('@sentry/node');
    
    Sentry.init({
     dsn: 'your-dsn',
     environment: process.env.NODE_ENV,
     tracesSampleRate: 1.0,
    });
    
    // 将Sentry与日志系统集成
    logger.on('error', (error) => {
     Sentry.captureException(error);
    });
    

六、安全考虑

  1. 敏感信息过滤

    const sensitiveFields = ['password', 'token', 'creditCard'];
    
    const redactFormat = format((info) => {
     sensitiveFields.forEach(field => {
       if (info[field]) {
         info[field] = '***REDACTED***';
       }
     });
     return info;
    });
    
  2. 日志文件权限设置

    chmod 640 /var/log/nodejs/*.log
    chown appuser:appgroup /var/log/nodejs/*.log
    

七、监控与告警

  1. 日志监控脚本示例

    #!/bin/bash
    ERROR_COUNT=$(grep -c "ERROR" /var/log/nodejs/app.log)
    if [ "$ERROR_COUNT" -gt 10 ]; then
     mail -s "High Error Rate Detected" admin@example.com <<< "Found $ERROR_COUNT errors in the last hour"
    fi
    
  2. Prometheus监控集成

    const client = require('prom-client');
    const errorCounter = new client.Counter({
     name: 'app_errors_total',
     help: 'Total number of application errors'
    });
    
    logger.on('error', () => errorCounter.inc());
    

通过以上优化方法,可以显著提高Linux环境下Node.js应用的日志管理效率、性能和安全性。