debian

Debian中Node.js日志清理最佳实践

小樊
39
2025-08-15 13:23:13
栏目: 编程语言

在Debian中清理Node.js日志的最佳实践如下:

  1. 使用logrotate工具(推荐)

    • 系统自带,自动轮转、压缩旧日志,配置简单。
    • 创建配置文件 /etc/logrotate.d/nodejs,内容示例:
      /path/to/logs/*.log {
        daily
        rotate 7
        compress
        missingok
        notifempty
        create 0640 root adm
      }
      
    • 测试配置:sudo logrotate -f /etc/logrotate.d/nodejs
  2. Node.js日志库集成

    • 使用winston+winston-daily-rotate-file实现代码级日志轮转:
      • 安装:npm install winston winston-daily-rotate-file
      • 配置示例:
        const winston = require('winston');
        const DailyRotateFile = require('winston-daily-rotate-file');
        const logger = winston.createLogger({
          transports: [
            new DailyRotateFile({
              filename: 'logs/app-%DATE%.log',
              datePattern: 'YYYY-MM-DD',
              maxSize: '20m',
              maxFiles: '14d',
              zippedArchive: true
            })
          ]
        });
        
    • 适用于需自定义日志格式或路径的场景。
  3. PM2日志管理(若使用PM2)

    • 启用内置轮转:pm2 install pm2-logrotate
    • 配置参数:
      pm2 set pm2-logrotate:max_size 10M   # 单个文件最大10MB
      pm2 set pm2-logrotate:retain 7      # 保留7天日志
      pm2 set pm2-logrotate:compress true # 压缩旧日志
      
    • 适合PM2管理的Node.js应用。
  4. 手动清理(临时方案)

    • 通过cron定时任务删除旧日志(不推荐长期使用):
      • 编辑crontabcrontab -e
      • 添加命令:0 0 * * * find /path/to/logs -type f -name "*.log" -mtime +7 -exec rm {} \;

最佳选择:优先使用logrotatewinston,兼顾自动化与灵活性;若使用PM2,直接配置其日志管理功能。定期检查日志目录权限,确保清理操作安全。

0
看了该问题的人还看了