debian

Node.js日志轮转怎么设置

小樊
33
2025-11-24 16:44:24
栏目: 编程语言

在 Node.js 应用程序中,可以使用第三方库 winstonwinston-daily-rotate-file 来实现日志轮转。以下是如何设置日志轮转的步骤:

  1. 首先,确保已经安装了 winstonwinston-daily-rotate-file。如果没有,请使用以下命令安装:
npm install winston winston-daily-rotate-file
  1. 在你的 Node.js 应用程序中,引入 winstonwinston-daily-rotate-file
const winston = require('winston');
const { DailyRotateFile } = require('winston-daily-rotate-file');
  1. 创建一个 winston.Logger 实例,并配置日志轮转选项:
const logger = new winston.Logger({
  level: 'info', // 日志级别
  format: winston.format.combine(
    winston.format.timestamp(), // 时间戳
    winston.format.printf(({ timestamp, level, message }) => {
      return `${timestamp} ${level}: ${message}`;
    })
  ),
  transports: [
    new DailyRotateFile({
      filename: 'logs/application-%DATE%.log', // 日志文件名格式
      datePattern: 'YYYY-MM-DD', // 日期格式
      zippedArchive: true, // 是否压缩归档日志
      maxSize: '20m', // 单个日志文件最大尺寸
      maxFiles: '14d' // 保留日志文件的天数
    })
  ]
});
  1. 使用 logger 实例记录日志:
logger.info('Hello, world!');

现在,你的 Node.js 应用程序将每天生成一个新的日志文件,并在达到最大尺寸或超过保留天数时自动轮转和压缩日志文件。

0
看了该问题的人还看了