centos-7.6系統默認安裝logrotate,默認的配置文件:node
/etc/logrotate.conf
/etc/logrotate.d/
logrotate.conf:爲主配置文件
logrotate.d:爲配置相關子系統,用於隔離每一個應用配置(Nginx、PHP、Tomcat...)
用於解決個別日誌文件過大,不易清理及查看
以haproxy 爲例linux
cat /etc/logrotate.d/haproxy /var/log/haproxy/haproxy.log { #文件絕對路徑,nginx日誌亦同上 daily #指定轉儲週期爲天天 rotate 20 #保留20天的日誌 missingok #若是日誌文件丟失,不進行顯示錯誤 notifempty #當日志文件爲空時,不進行轉儲 dateext #加上日誌格式 compress #經過gzip壓縮轉儲後的日誌 sharedscripts #轉儲完成後運行腳本,postrotate-endscript間爲腳本內容,腳本效果爲重啓rsyslogd服務。 postrotate systemctl restart rsyslog.service endscript }
測試配置文件
logrotate -d /etc/logrotate.d/haproxy
該服務由anacron調用
anacron默認配置以下
修改該服務的調用時間nginx
cat /etc/anacrontab # /etc/anacrontab: configuration file for anacron # See anacron(8) and anacrontab(5) for details. SHELL=/bin/sh PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root # the maximal random delay added to the base delay of the jobs RANDOM_DELAY=45 # the jobs will be started during the following hours only #默認爲3點到22點隨機延遲45分鐘執行,修改成3點到5點 START_HOURS_RANGE=3-5 #period in days delay in minutes job-identifier command 1 5 cron.daily nice run-parts /etc/cron.daily 7 25 cron.weekly nice run-parts /etc/cron.weekly @monthly 45 cron.monthly nice run-parts /etc/cron.monthly
效果以下centos
-rw------- 1 root root 3030916 Jul 1 03:48 haproxy.log-20190701.gz -rw------- 1 root root 3870655 Jul 2 03:24 haproxy.log-20190702.gz -rw------- 1 root root 4569410 Jul 3 03:39 haproxy.log-20190703.gz -rw------- 1 root root 3715970 Jul 4 03:33 haproxy.log-20190704.gz
Logrotate中其餘可配置參數,具體以下:dom
compress //經過gzip 壓縮轉儲之後的日誌 nocompress //不作gzip壓縮處理 copytruncate //用於還在打開中的日誌文件,把當前日誌備份並截斷;是先拷貝再清空的方式,拷貝和清空之間有一個時間差,可能會丟失部分日誌數據。 nocopytruncate //備份日誌文件不過不截斷 create mode owner group //輪轉時指定建立新文件的屬性,如create 0777 nobody nobody nocreate //不創建新的日誌文件 delaycompress //和compress 一塊兒使用時,轉儲的日誌文件到下一次轉儲時才壓縮 nodelaycompress //覆蓋 delaycompress 選項,轉儲同時壓縮。 missingok //若是日誌丟失,不報錯繼續滾動下一個日誌 errors address //專儲時的錯誤信息發送到指定的Email 地址 ifempty //即便日誌文件爲空文件也作輪轉,這個是logrotate的缺省選項。 notifempty //當日志文件爲空時,不進行輪轉 mail address //把轉儲的日誌文件發送到指定的E-mail 地址 nomail //轉儲時不發送日誌文件 olddir directory //轉儲後的日誌文件放入指定的目錄,必須和當前日誌文件在同一個文件系統 noolddir //轉儲後的日誌文件和當前日誌文件放在同一個目錄下 sharedscripts //運行postrotate腳本,做用是在全部日誌都輪轉後統一執行一次腳本。若是沒有配置這個,那麼每一個日誌輪轉後都會執行一次腳本 prerotate //在logrotate轉儲以前須要執行的指令,例如修改文件的屬性等動做;必須獨立成行 postrotate //在logrotate轉儲以後須要執行的指令,例如從新啓動 (kill -HUP) 某個服務!必須獨立成行 daily //指定轉儲週期爲天天 weekly //指定轉儲週期爲每週 monthly //指定轉儲週期爲每個月 rotate count //指定日誌文件刪除以前轉儲的次數,0 指沒有備份,5 指保留5 個備份 dateext //使用當期日期做爲命名格式 dateformat .%s //配合dateext使用,緊跟在下一行出現,定義文件切割後的文件名,必須配合dateext使用,只支持 %Y %m %d %s 這四個參數 size(或minsize) log-size //當日志文件到達指定的大小時才轉儲,log-size能指定bytes(缺省)及KB (sizek)或MB(sizem). 當日志文件 >= log-size 的時候就轉儲。 如下爲合法格式:(其餘格式的單位大小寫沒有試過) size = 5 或 size 5 (>= 5 個字節就轉儲) size = 100k 或 size 100k size = 100M 或 size 100M