Linux自帶的logrotate程序來解決catalina.out的日誌輪轉問題.md

  • 1.首先編輯logrotate.conf文件,打開compress選項(去掉註釋)
[root@localhost ~]#  cat /etc/logrotate.conf | grep -v "^$"| grep -v "#"
weekly
rotate 4
create
compress
include /etc/logrotate.d
  • 2.添加指定文件,在/etc/logrotate.d/目錄下新建一個名爲tomcat的文件
[root@localhost ~]# cat > /etc/logrotate.d/tomcat <<EOF
/home/tomcat/utr/logs/catalina.out{ #要輪轉的文件
    copytruncate    # 創建新的catalina.out副本後,截斷源catalina.out文件
    daily    # 每天進行catalina.out文件的輪轉
    rotate 7     # 至多保留7個副本
    missingok    # 如果要輪轉的文件丟失了,繼續輪轉而不報錯
    compress     # 使用壓縮的方式(節省硬盤空間;一個2~3GB的日誌文件可以壓縮成60MB左右)
    size 16M     # 當catalina.out文件大於16MB時,就輪轉
    dateext
    dateformat .%Y-%m-%d
    extension .log
    notifempty
}
EOF

參數說明:
copytruncate #備份日誌並截斷源文件
nocopytruncate # 備份日誌文件不截斷
dateext #使用當期日期作爲命名格式
notifempty #當日志文件爲空時,不進行輪轉
daily # 每天進行文件的輪轉
size 16M # 當文件大於16MB時,就會輪轉
rotate 30 #指定日誌文件刪除之前轉儲的次數

  • 3.執行方式
    ①自動執行原理

    1.每天晚上crond守護進程會運行在/etc/cron.daily目錄中的任務列表;
    2.與logrotate相關的腳本也在/etc/cron.daily目錄中。運行的方式爲"/usr/bin/logrotate /etc/logrotate.conf";
    3./etc/logrotate.conf文件include了/etc/logrotate.d/目錄下的所有文件。還包括我們上面剛創建的tomcat文件;
    4./etc/logrotate.d/tomcat文件會觸發/usr/local/apache-tomcat-8.0.28/logs/catalina.out文件的輪轉。

    ②手動執行:logrotate /etc/logrotate.conf

    ③只輪轉剛剛的tomcat配置文件:logrotate --force /etc/logrotate.d/tomcat

  • 3.自動執行時間

[root@localhost ~]# 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
START_HOURS_RANGE=3-22

#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

裏面有個
START_HOURS_RANGE=3-22 這個是開始時間
RANDOM_DELAY=45 這個是隨機的延遲時間,表示最大45min.

還有個
1 5 cron.daily nice run-parts /etc/cron.daily
第一個是Recurrence period 第二個是延遲時間,所以cron.daily會在3:22+(5,45)這個時間段執行,/etc/cron.daily是個文件夾

參考文獻

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章