Systemd 是现代 Linux 系统的标准初始化系统,提供了更强大的定时任务功能。
创建 /etc/systemd/system/clean-logs.service
文件:
[Unit]
Description=Clean system logs
[Service]
Type=oneshot
ExecStart=/usr/bin/find /var/log -type f -name "*.log" -mtime +7 -exec truncate -s 0 {} \;
ExecStart=/usr/bin/find /var/log -type f -name "*.gz" -mtime +30 -delete
创建 /etc/systemd/system/clean-logs.timer
文件:
[Unit]
Description=Run log cleanup daily
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now clean-logs.timer
systemctl list-timers clean-logs.timer
创建 /usr/local/bin/clean-logs.sh
文件:
#!/bin/bash
# 清空7天前的.log文件内容
find /var/log -type f -name "*.log" -mtime +7 -exec truncate -s 0 {} \;
# 删除30天前的压缩日志
find /var/log -type f -name "*.gz" -mtime +30 -delete
# 可选:记录清理操作
logger "System logs cleaned by clean-logs.sh"
赋予执行权限:
sudo chmod +x /usr/local/bin/clean-logs.sh
编辑 root 用户的 crontab:
sudo crontab -e
添加以下内容(每天凌晨3点执行):
0 3 * * * /usr/local/bin/clean-logs.sh
sudo crontab -l
对于更专业的日志管理,可以考虑使用系统自带的 logrotate:
创建 /etc/logrotate.d/mycustomlogs
文件:
/var/log/myapp/*.log {
daily
missingok
rotate 7
compress
delaycompress
notifempty
create 0640 root adm
sharedscripts
postrotate
/usr/lib/rsyslog/rsyslog-rotate
endscript
}
sudo logrotate -d /etc/logrotate.d/mycustomlogs
sudo logrotate -vf /etc/logrotate.d/mycustomlogs
# 清理超过100MB的日志文件
find /var/log -type f -name "*.log" -size +100M -exec truncate -s 0 {} \;
# 清理但不包括secure日志
find /var/log -type f -name "*.log" ! -name "secure" -mtime +7 -exec truncate -s 0 {} \;
# 在清理脚本中添加邮件通知
echo "Logs cleaned on $(hostname) at $(date)" | mail -s "Log Cleanup Report" admin@example.com
选择哪种方法取决于您的系统环境和个人偏好。Systemd timer 更适合现代 Linux 系统,而 crontab 则更通用。logrotate 提供了最专业的日志管理功能。