1.問題背景,nginx日志過大不好刪除
[root@localhost cron.daily]# cd /lk/nginx/log/
[root@localhost log]# ll
總用量 2386188
-rw-r--r--. 1 root root 2078699697 5月 ? 9 13:02 access.log
-rw-r--r--. 1 root root ? ? ?11138 5月 ? 6 10:28 error.log
[root@localhost log]# du -sh *
2.3G?? ?access.log
12K?? ?error.log
[root@localhost log]# pwd
/lk/nginx/log
[root@localhost log]#
2,要求:日志只保留7天,按天分割
?
?3,實現步驟
1,安裝軟件
yun -y install?crond && systemctl restart crond &&?systemctl enable crond
2,創建日志切割配置?
vi /etc/logrotate.d/nginx
/lk/nginx/log/access.log {
? ? daily
? ? rotate 4
? ? missingok
? ? compress
? ? delaycompress
? ? notifempty
? ? create 0640 root root
? ? dateext
? ? dateformat -%Y%m%d
}
?3,測試配置
sudo logrotate -d /etc/logrotate.d/nginx
這將模擬日志切割,且不會實際修改文件。如果配置正確且沒有錯誤,你可以去掉 -d
參數,執行實際的日志切割:-f 強制切割
sudo sudo logrotate -f /etc/logrotate.d/nginx
4. 自動化
設置時間
crontab -e
59 23 * * * /usr/sbin/logrotate -f /etc/logrotate.d/nginx
這表示 logrotate
會在每天在 23:59 自動執行日志輪轉?
確保 Cron 服務正在運行
sudo systemctl status?crond &&?systemctl restart crond