天天看點

用 Linux自帶的logrotate 來管理日志

大家可能都有管理日志的需要,比如定時壓縮日志,或者當日志超過一定大小時就自動分裂成兩個檔案等。最近就接到這樣一個小任務。我們的程式用的是C語言,用log4cpp的library來實作日志記錄。但是問題是log4cpp并不支援當日志超過一定大小時自動分裂的功能,隻能從頭覆寫之前的日志,但這顯然不是我們想要的。經過一番搜尋,我發現其實Linux自帶的logrotate指令就能夠實作這樣的功能。

這是logrotate的一段簡介:

The logrotate utility is designed to simplify the administration of log files on a system which generates a lot of log files. Logrotate allows for the automatic rotation compression, removal and mailing of log files. Logrotate can be set to handle a log file daily, weekly, monthly or when the log file gets to a certain size.      

為了使用它,主要有兩個地方需要修改一下:一個是/etc/logrotate.conf,另一個是/etc/logrotate.d/下面的檔案。

你既可以在logrotate.conf中直接定義如何處理你的log檔案,也可以在/logrotate.d/下面針對自己的log建立一個對應的檔案來定義處理log的行為。

這裡是logrotate指令的詳細解釋的連結:http://linuxcommand.org/man_pages/logrotate8.html

下面是一個具體例子:

/var/log/news/news.crit {
           monthly
           rotate 2
           olddir /var/log/news/old
           missingok
           postrotate
                                     kill -HUP ‘cat /var/run/inn.pid‘
           endscript
           nocompress
       }      

monthly:說明是一個月進行一次處理,常用的還有daily,weekly

rotate 2:意思是說最多保留兩個備份,多餘的老的日志就被覆寫了

olddir:定義了舊的日志存儲在哪裡

missingok:意思是如果上述news.crit檔案找不到的話也不報錯,直接跳過

postrotate ... endscript:它們以及中間的指令定義了在執行完rotate之後要做什麼,一般主要是為了讓使用該日志檔案的程式知道這個日志被替換了,需要重新打開這個檔案

nocompress:說明舊日志不需要被壓縮儲存

logrotate定義了如何處理日志,而它本身則是被crond定時調用的。crond是一個Unix系作業系統中的定時排程軟體,下面一段文字是從wiki上抄來的:

The software utility Cron is a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. It typically automates system maintenance or administration—though its general-purpose nature makes it useful for things like connecting to the Internet and downloading email at regular intervals.      

預設的logrotate是一天運作一次,它的腳本被放在/etc/cron.daily/下面。除了cron.daily外還有cron.weekly,cron.monthly,cron.hourly等分别對應不同的頻率,你可以根據自己的需要把腳本放在不同的檔案夾下面。在設定外所有東西以後,别忘了使用chkconfig crond on來保證它會一直開機運作。然後就大工告成了。

----------------------------------------------------------------

作者:好大一片雲

部落格位址:http://www.cnblogs.com/zhutianshi/

轉載聲明:可以轉載, 但必須以超連結形式标明文章原始出處和作者資訊及版權聲明,謝謝合作!

用 Linux自帶的logrotate 來管理日志

This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

繼續閱讀