Linux中Node.js日志轮转主要有以下几种策略:
使用logrotate工具(系统级)
sudo apt-get install logrotate(Debian/Ubuntu)或sudo yum install logrotate(CentOS/RHEL)。/etc/logrotate.d/下创建配置文件(如node-app),指定日志路径、轮转周期(如daily)、保留数量(如rotate 7)、压缩(compress)等参数。sudo logrotate -f /etc/logrotate.d/node-app手动触发轮转。使用PM2日志管理(进程级)
sudo npm install pm2 -g。pm2 install pm2-logrotate,并配置参数(如max_size、retain、compress)。使用Node.js日志库(应用级)
winston-daily-rotate-file插件,通过代码配置轮转规则(如按天/按大小分割、压缩、保留天数)。const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const logger = winston.createLogger({
transports: [
new DailyRotateFile({
filename: 'app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
})
]
});
```。
log4js也支持按文件大小或时间轮转。选择建议:
logrotate,适合多应用场景,配置简单且与系统集成紧密。winston,灵活性高,可定制化轮转逻辑(如按业务模块分割日志)。