在Debian中清理Node.js日志的最佳實踐如下:
使用logrotate工具(推薦)
/etc/logrotate.d/nodejs
,內容示例:/path/to/logs/*.log {
daily
rotate 7
compress
missingok
notifempty
create 0640 root adm
}
sudo logrotate -f /etc/logrotate.d/nodejs
。Node.js日志庫集成
winston
+winston-daily-rotate-file
實現代碼級日志輪轉:
npm install winston winston-daily-rotate-file
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const logger = winston.createLogger({
transports: [
new DailyRotateFile({
filename: 'logs/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '20m',
maxFiles: '14d',
zippedArchive: true
})
]
});
PM2日志管理(若使用PM2)
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M # 單個文件最大10MB
pm2 set pm2-logrotate:retain 7 # 保留7天日志
pm2 set pm2-logrotate:compress true # 壓縮舊日志
手動清理(臨時方案)
cron
定時任務刪除舊日志(不推薦長期使用):
crontab
:crontab -e
0 0 * * * find /path/to/logs -type f -name "*.log" -mtime +7 -exec rm {} \;
。最佳選擇:優先使用logrotate
或winston
,兼顧自動化與靈活性;若使用PM2,直接配置其日志管理功能。定期檢查日志目錄權限,確保清理操作安全。