debian

Debian Node.js 日志清理方法

小樊
47
2025-08-23 15:10:24
栏目: 编程语言

Debian系统清理Node.js日志的常用方法如下:

  1. 手动清理

    • 定位日志文件(通常在/var/log/或应用自定义路径)。
    • 使用rm命令删除,如sudo rm /path/to/logs/*.log,或结合find命令按时间删除(如find /path/to/logs -type f -mtime +7 -exec rm {} \;)。
  2. 使用logrotate工具(推荐)

    • 安装:sudo apt-get install logrotate
    • 配置:在/etc/logrotate.d/下创建配置文件(如nodejs),添加规则:
      /path/to/logs/*.log {
        daily
        rotate 7
        compress
        missingok
        notifempty
        create 0640 root adm
      }
      
      rotate 7保留7天日志,compress压缩旧日志)。
    • 测试配置:sudo logrotate -f /etc/logrotate.d/nodejs
  3. 通过Node.js日志库自动管理

    • 使用winston+winston-daily-rotate-file插件,在代码中配置日志轮转(如按天分割、保留14天)。
    • 示例代码:
      const winston = require('winston');
      const DailyRotateFile = require('winston-daily-rotate-file');
      const logger = winston.createLogger({
        transports: [
          new DailyRotateFile({
            filename: '/path/to/logs/app-%DATE%.log',
            datePattern: 'YYYY-MM-DD',
            maxSize: '20m',
            maxFiles: '14d',
            zippedArchive: true
          })
        ]
      });
      
  4. Cron定时任务

    • 编辑crontabcrontab -e,添加定时清理命令(如每天凌晨1点删除7天前日志):
      0 1 * * * find /path/to/logs -type f -name "*.log" -mtime +7 -exec rm -f {} \;

注意:优先使用logrotate或日志库的自动管理功能,避免手动操作遗漏。

0
看了该问题的人还看了