用 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來保證它會一直開機運行。然后就大工告成了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM