Debian系统清理Node.js日志的常用方法如下:
手动清理
/var/log/
或应用自定义路径)。rm
命令删除,如sudo rm /path/to/logs/*.log
,或结合find
命令按时间删除(如find /path/to/logs -type f -mtime +7 -exec rm {} \;
)。使用logrotate工具(推荐)
sudo apt-get install logrotate
。/etc/logrotate.d/
下创建配置文件(如nodejs
),添加规则:/path/to/logs/*.log {
daily
rotate 7
compress
missingok
notifempty
create 0640 root adm
}
(rotate 7
保留7天日志,compress
压缩旧日志)。sudo logrotate -f /etc/logrotate.d/nodejs
。通过Node.js日志库自动管理
winston
+winston-daily-rotate-file
插件,在代码中配置日志轮转(如按天分割、保留14天)。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',
maxSize: '20m',
maxFiles: '14d',
zippedArchive: true
})
]
});
Cron定时任务
crontab
:crontab -e
,添加定时清理命令(如每天凌晨1点删除7天前日志):0 1 * * * find /path/to/logs -type f -name "*.log" -mtime +7 -exec rm -f {} \;
。注意:优先使用logrotate
或日志库的自动管理功能,避免手动操作遗漏。