日志清理
本文所有的脚本保存在 /data/septvean/bash/log-cleanup 目录
执行 deploy.sh 脚本部署脚本。
- ✅ 只清理日志,不破坏目录结构
- ✅ truncate 优先于 rm(系统服务更安全)
- ✅ journalctl 用官方 vacuum
- ✅ 可扩展其它日志
- ✅ 适合每周执行一次
📄 /usr/sbin/log-cleanup.sh
#!/bin/bash
set -euo pipefail
# ------------------------
# 基本变量
# ------------------------
LOG_DATE="$(date '+%F %T')"
LOG_FILE="/var/log/log-cleanup.log"
echo "[$LOG_DATE] log cleanup start" >>"$LOG_FILE"
# ------------------------
# 1. 清理 dnf 日志
# ------------------------
rm -fv /var/log/dnf.* >>"$LOG_FILE" 2>&1 || true
# ------------------------
# 2. truncate 系统日志(不删除文件)
# ------------------------
: >/var/log/cron
: >/var/log/messages
# 可选扩展
: >/var/log/secure || true
: >/var/log/maillog || true
: >/var/log/spooler || true
# ------------------------
# 3. systemd journal 清理(保留 1 周)
# ------------------------
journalctl --vacuum-time=1w >>"$LOG_FILE" 2>&1
# ------------------------
# 4. 扩展:清理过期 .gz / .old 日志(保留 7 天)
# ------------------------
find /var/log -type f \
\( -name "*.gz" -o -name "*.old" -o -name "*.log.*" \) \
-mtime +7 -print -delete >>"$LOG_FILE" 2>&1
# ------------------------
# 结束
# ------------------------
echo "[$(date '+%F %T')] log cleanup done" >>"$LOG_FILE"
: >/var/log/messages
- 不删除 inode
- systemd / rsyslog 不会崩
- 这是 生产环境标准做法
rm -fv /var/log/dnf.*
- dnf 不依赖长期日志
- 删除比 truncate 更干净
journalctl --vacuum-time=1w
- 官方支持
- 不要手动 rm /var/log/journal
*.gz
*.old
*.log.1
*.log.2
只清理 轮转后的历史日志
chmod +x /usr/sbin/log-cleanup.sh
chown root:root /usr/sbin/log-cleanup.sh
crontab -e
添加:
0 3 * * 0 /usr/sbin/log-cleanup.sh
含义:
- 每周日
- 凌晨 03:00
- root 执行
📄 /etc/systemd/system/log-cleanup.service
[Unit]
Description=Weekly Log Cleanup
[Service]
Type=oneshot
ExecStart=/usr/sbin/log-cleanup.sh
📄 /etc/systemd/system/log-cleanup.timer
[Unit]
Description=Run log cleanup weekly
[Timer]
OnCalendar=weekly
Persistent=true
[Install]
WantedBy=timers.target
启用:
systemctl daemon-reload
systemctl enable --now log-cleanup.timer
journalctl --vacuum-size=500M
或配置:
# /etc/systemd/journald.conf
SystemMaxUse=500M
find ... -print
- 适合 AlmaLinux 9 生产环境
- 不会破坏 systemd / rsyslog
- 可扩展、可审计、有日志
- cron / timer 都支持