Debian下Node.js日志清理与轮转实用指南
一 常用方案总览
二 系统级 logrotate 配置
sudo apt-get update && sudo apt-get install -y logrotate/var/www/myapp/logs/*.log {
daily
missingok
rotate 7
compress
delaycompress
notifempty
create 0640 www-data www-data
postrotate
# 可选:通知应用重新打开日志(如 PM2 可用 pm2 reload logs)
# pm2 reload logs >/dev/null 2>&1 || true
endscript
}
sudo logrotate -d /etc/logrotate.d/nodejssudo logrotate -f /etc/logrotate.d/nodejs三 使用 PM2 管理时的日志策略
pm2 install pm2-logrotatepm2 set pm2-logrotate:max_days 7pm2 set pm2-logrotate:compress truepm2 set pm2-logrotate:rotateInterval '0 0 * * *'pm2 logs my-app四 应用内日志库轮转示例
npm i winston winston-daily-rotate-fileconst winston = require('winston');
const { DailyRotateFile } = require('winston-daily-rotate-file');
const transport = new DailyRotateFile({
filename: '/var/www/myapp/logs/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
});
const logger = winston.createLogger({
level: 'info',
transports: [transport]
});
npm i pino pino-rotateconst pino = require('pino');
const rotate = require('pino-rotate');
rotate({
period: '1d',
path: '/var/www/myapp/logs',
maxFiles: 7,
gzip: true
});
五 兜底方案与运维建议
0 0 * * * find /var/www/myapp/logs -type f -name "*.log" -mtime +7 -exec rm -f {} \;rm app.log 后重建;使用 logrotate 的 create 或让应用支持重新打开日志(如发送信号或重载)。