在 Node.js 应用程序中,可以使用第三方库 winston
和 winston-daily-rotate-file
来实现日志轮转策略。以下是如何设置日志轮转策略的步骤:
- 首先,确保已经安装了
winston
和winston-daily-rotate-file
。如果没有,请使用以下命令安装:
npm install winston winston-daily-rotate-file
- 在你的 Node.js 应用程序中,创建一个名为
logger.js
的文件,并添加以下代码:
const winston = require('winston'); const { format } = winston; const DailyRotateFile = require('winston-daily-rotate-file'); // 日志格式 const logFormat = format.combine( format.timestamp(), format.printf(({ timestamp, level, message }) => { return `${timestamp} [${level.toUpperCase()}]: ${message}`; }) ); // 创建一个名为 dailyRotateFile 的传输器 const dailyRotateFile = new DailyRotateFile({ filename: 'logs/app-%DATE%.log', // 日志文件名模板 datePattern: 'YYYY-MM-DD', // 日期格式 zippedArchive: true, // 是否压缩归档日志文件 maxSize: '20m', // 单个日志文件的最大尺寸 maxFiles: '14d' // 保留日志文件的天数 }); // 创建一个 winston 日志记录器实例 const logger = winston.createLogger({ level: 'info', // 日志级别 format: logFormat, transports: [ new winston.transports.Console(), // 将日志输出到控制台 dailyRotateFile // 将日志输出到按日期轮转的文件 ] }); module.exports = logger;
- 在你的主要应用程序文件(例如
app.js
)中,引入并使用logger.js
:
const logger = require('./logger'); // 使用 logger 记录日志 logger.info('Server is running on port 3000');
现在,你的 Node.js 应用程序将使用 winston-daily-rotate-file
设置的日志轮转策略。每天都会创建一个新的日志文件,并根据配置的最大文件尺寸和保留天数进行轮转和压缩。