阅读量:3
在 Node.js 应用程序中,可以使用第三方库 winston 和 winston-daily-rotate-file 来实现日志轮转。以下是如何设置日志轮转的步骤:
- 首先,确保已经安装了
winston和winston-daily-rotate-file。如果没有,请使用以下命令安装:
npm install winston winston-daily-rotate-file
- 在你的 Node.js 应用程序中,引入
winston和winston-daily-rotate-file:
const winston = require('winston');
const { DailyRotateFile } = require('winston-daily-rotate-file');
- 创建一个
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' // 保留日志文件的天数
})
]
});
- 使用
logger实例记录日志:
logger.info('Hello, world!');
现在,你的 Node.js 应用程序将每天生成一个新的日志文件,并在达到最大尺寸或超过保留天数时自动轮转和压缩日志文件。
以上就是关于“Node.js日志轮转怎么设置”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm