| 指令 | 說明 | 示例 |
| daily/weekly/monthly/yearly | 輪轉頻率 | daily |
| size 100M | 達到大小即輪轉(優先於時間) | size 100M |
| rotate 5 | 保留歸檔數量,超過刪除最舊 | rotate 12 |
| compress | gzip 壓縮歸檔 | compress |
| delaycompress | 延遲壓縮:最新歸檔不壓,下次再壓 | delaycompress |
| missingok | 文件不存在不報錯 | missingok |
| notifempty | 空文件不輪轉 | notifempty |
| create 644 root root | 輪轉後創建新文件(權限、擁有者) | create 640 nginx adm |
| dateext | 歸檔名含日期:log-20240115.gz | dateext |
| dateformat -%Y%m%d | 自定義日期格式 | dateformat -%Y-%m-%d |
| sharedscripts | postrotate 腳本只執行一次(多文件匹配時) | sharedscripts |
| postrotate/endscript | 輪轉後執行腳本(如 reload 服務) | 見下文 |
| mail address | 郵件發送歸檔 | mail admin@example.com |
| olddir /path | 歸檔存放目錄 | olddir /var/log/archive |
| su root root | 以指定用戶執行輪轉 | su nginx nginx |
三、三大經典配置模板
模板 1:時間驅動 + 壓縮 + 延遲壓縮 + 服務重載(Nginx 標準)
/var/log/nginx/*.log {
daily
rotate 30
compress
delaycompress
missingok
notifempty
create 640 nginx adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
模板 2:大小驅動(高頻日誌、防止單文件過大)
/var/log/app/access.log {
size 500M
rotate 10
create 644 app app
postrotate
systemctl reload app > /dev/null
endscript
}
模板 3:帶日期後綴、長期保留(審計/合規)
/var/log/audit/audit.log {
monthly
rotate 365
dateext
dateformat -%Y%m%d
compress
missingok
notifempty
create 600 root root
olddir /var/log/audit/archive
}
四、調試與驗證技巧
1. 演練模式(不實際輪轉)
logrotate -d /etc/logrotate.d/nginx
# 輸出決策邏輯:need rotating? no/yes、將執行的動作
2. 強制執行(忽略條件)
logrotate -vf /etc/logrotate.d/nginx
# -v 詳細輸出,-f 強制
3. 指定狀態文件(隔離測試)
logrotate -vf -s /tmp/logrotate-status /etc/logrotate.d/nginx
4. 手動觸發每日任務
/etc/cron.daily/logrotate
五、systemd 定時器替代 cron(現代方式)
# /etc/systemd/system/logrotate.timer
[Unit]
Description=Daily log rotation
[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=1h
[Install]
WantedBy=timers.target
# /etc/systemd/system/logrotate.service
[Unit]
Description=Log rotation
[Service]
Type=oneshot
ExecStart=/usr/sbin/logrotate /etc/logrotate.conf
systemctl enable --now logrotate.timer
六、常見坑點
| 現象 | 原因 | 解決 |
| 日誌不輪轉 | 未匹配通配符 / 權限不足 / notifempty 但文件為空 | 檢查路徑、權限、ls -l 確認大小 |
| 服務重載失敗 | postrotate 腳本路徑錯、PID 文件不存在 | 用 systemctl reload 或 kill -USR1 主進程 |
| 歸檔文件權限錯誤 | create 指令缺失或 su 指令錯誤 | 顯式指定 create 640 user group |
| 磁盤仍滿 | rotate 數量太少、未壓縮、舊文件在 olddir 佔用空間 | 增大 rotate、啟用 compress、清理 olddir |
總結
logrotate 配置核心:頻率、保留數、壓縮策略、postrotate 重載服務。生產環境建議:按天輪轉 + 按大小兜底 + dateext 日期後綴 + 共享腳本重載。善用 logrotate -d 演練驗證,配合 systemd timer 替代 cron 獲得更精確調度。
copyright ©
萬盛學電腦網 all rights reserved