debian

Debian Node.js日志轮转策略有哪些

小樊
39
2025-11-06 15:59:51
栏目: 编程语言

Debian系统中Node.js日志轮转的主要策略及实现方式

1. 使用系统级工具logrotate(推荐)

logrotate是Debian系统自带的日志管理工具,支持按时间/大小轮转、压缩、删除旧日志等功能,适用于大多数Node.js应用。
配置步骤

2. 使用Node.js日志库内置轮转功能(灵活可控)

若应用使用winstonpino等日志库,可通过内置或第三方模块实现日志轮转,适合需要定制化轮转规则的场景。

(1)winston + winston-daily-rotate-file

winston是Node.js最流行的日志库,通过winston-daily-rotate-file模块实现按时间/大小轮转
配置示例

const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');

const transport = new DailyRotateFile({
  filename: 'logs/application-%DATE%.log', // 日志文件路径(含日期占位符)
  datePattern: 'YYYY-MM-DD',               // 日期格式(每天一个文件)
  zippedArchive: true,                     // 压缩旧日志(.gz格式)
  maxSize: '20m',                          // 单个日志文件最大大小(20MB)
  maxFiles: '14d'                          // 保留最近14天的日志
});

const logger = winston.createLogger({
  transports: [transport]                  // 添加轮转传输
});

说明%DATE%会被替换为当前日期(如application-2025-11-06.log),旧日志会自动压缩并保留指定天数。

(2)pino + pino-rotate

pino是高性能日志库,通过pino-rotate模块实现按时间轮转
配置示例

const pino = require('pino');
const pinoRotate = require('pino-rotate');

const logger = pino({
  level: 'info',
  transport: pinoRotate({
    period: '1d',          // 轮转周期(每天)
    path: '/path/to/logs/application.log', // 日志文件路径
    size: '20m',           // 单个文件最大大小(20MB)
    compress: true         // 压缩旧日志
  })
});

说明period支持1d(每天)、1h(每小时)等,size可限制单个文件大小,避免磁盘空间耗尽。

3. 使用系统定时任务(cron,基础方案)

若不想依赖第三方工具,可通过cron定时任务定期清理/轮转日志(适合简单场景)。
配置步骤

说明find命令查找/path/to/logs目录下7天前(-mtime +7)的.log文件并删除(-exec rm -f {} \;)。

以上策略可根据实际需求选择:

0
看了该问题的人还看了