以下是Ubuntu下清理Node.js日志的常用技巧:
使用logrotate工具(推荐)
sudo apt-get install logrotate
/etc/logrotate.d/
下创建nodejs
文件,添加以下内容:/path/to/logs/*.log {
daily
rotate 7
compress
missingok
notifempty
create 0640 root adm
}
(daily
表示每日轮转,rotate 7
保留7天日志,compress
压缩旧日志)通过cron定时任务手动清理
crontab -e
0 1 * * * find /path/to/logs -type f -name "*.log" -mtime +7 -exec rm -f {} \;
利用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: '/path/to/logs/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
})
]
});
直接使用系统命令(谨慎操作)
.log
文件:sudo find /var/log -type f -name "*.log" -exec truncate -s 0 {} \;
sudo rm -rf /path/to/logs/*.log
(建议先备份)注意:清理前确保无重要数据在日志中,优先使用logrotate
或日志库功能,避免误删。