Node.js日志切割如何操作

作者:袖梨 2026-06-28

在Node.js中,可以使用第三方库winstonwinston-daily-rotate-file来实现日志切割。以下是一个简单的示例:

Node.js日志如何进行切割

  1. 首先,确保已经安装了winstonwinston-daily-rotate-file这两个库。如果没有,请使用以下命令安装:
npm install winston winston-daily-rotate-file
  1. 创建一个名为logger.js的文件,并在其中设置日志记录器和日志切割:
const winston = require('winston');const { format } = winston;const { combine, timestamp, printf } = format;const DailyRotateFile = require('winston-daily-rotate-file');// 自定义日志格式const myFormat = printf(({ timestamp, level, message }) => {return `${timestamp} ${level}: ${message}`;});// 创建一个日志记录器const logger = winston.createLogger({level: 'info',format: combine(timestamp(),myFormat),transports: [new DailyRotateFile({filename: 'logs/application-%DATE%.log', // 日志文件名格式datePattern: 'YYYY-MM-DD', // 按日期切割日志zippedArchive: true, // 是否压缩归档日志maxSize: '20m', // 单个日志文件最大尺寸maxFiles: '14d' // 保留最近14天的日志文件})]});module.exports = logger;
  1. 在你的Node.js应用程序中使用logger.js
const logger = require('./logger');logger.info('Hello, world!');logger.error('An error occurred');

这样,你的Node.js应用程序将会在每天生成一个新的日志文件,并根据配置进行日志切割和压缩。

相关文章

精彩推荐