日志轮转是管理应用程序日志的重要功能,可以防止日志文件无限增长占用磁盘空间。以下是几种在Node.js中实现日志轮转的方法:
const winston = require('winston');
require('winston-logrotate');
const logger = new winston.Logger({
transports: [
new winston.transports.Rotate({
file: '/path/to/your/logfile.log',
timestamp: true,
max: '100m', // 每个日志文件最大100MB
keep: 5, // 保留5个备份文件
compress: true // 压缩旧日志
})
]
});
/etc/logrotate.d/your-node-app
:/path/to/your/node-app.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
copytruncate
dateext
}
daily
: 每天轮转rotate 30
: 保留30个旧日志文件compress
: 压缩旧日志copytruncate
: 复制后清空原文件,而不是移动dateext
: 使用日期作为日志文件后缀如果你使用PM2管理Node.js进程:
# 安装PM2日志轮转模块
pm2 install pm2-logrotate
# 配置轮转参数
pm2 set pm2-logrotate:max_size 100M # 每个日志文件最大100MB
pm2 set pm2-logrotate:retain 10 # 保留10个日志文件
pm2 set pm2-logrotate:compress true # 压缩旧日志
pm2 set pm2-logrotate:dateFormat YYYY-MM-DD_HH-mm-ss
const log4js = require('log4js');
log4js.configure({
appenders: {
file: {
type: 'file',
filename: 'app.log',
maxLogSize: 10485760, // 10MB
backups: 5, // 保留5个备份
compress: true // 压缩备份
}
},
categories: {
default: { appenders: ['file'], level: 'info' }
}
});
const logger = log4js.getLogger();
const bunyan = require('bunyan');
const rfs = require('rotating-file-stream');
const stream = rfs.createStream('app.log', {
size: '10M', // 每个文件10MB
interval: '1d', // 每天轮转
compress: 'gzip', // 压缩旧日志
path: '/path/to/logs'
});
const logger = bunyan.createLogger({
name: 'myapp',
streams: [{
level: 'info',
stream: stream
}]
});
选择哪种方法取决于你的具体需求、部署环境和性能要求。生产环境推荐使用专门的日志管理工具或服务。