Linux Node.js 日志清理策略
一 常用策略总览
二 配置示例
/var/log/node-app/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 0640 root adm
copytruncate
dateext
}
sudo logrotate -f /etc/logrotate.d/node-app。npm i winston winston-daily-rotate-fileconst winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const transport = new DailyRotateFile({
filename: '/var/log/node-app/application-%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
});
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [transport]
});
pm2 install pm2-logrotatepm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 7
pm2 set pm2-logrotate:compress true
pm2 set pm2-logrotate:rotateInterval "0 0 * * *"
pm2 restart all
[Service]
ExecStart=/usr/bin/node /path/to/app.js
StandardOutput=append:/var/log/node-app/stdout.log
StandardError=append:/var/log/node-app/stderr.log
SyslogIdentifier=node-app
if $programname == 'node-app' then /var/log/node-app.log & stop;重启服务:sudo systemctl daemon-reload && sudo systemctl restart node-app。0 0 * * * find /var/log/node-app -type f -name "*.log" -mtime +7 -delete0 1 * * * /opt/scripts/clean_logs.sh。三 选型与组合建议
四 关键注意事项
find ... -mtime +7 -print)。