用 Linux自带的logrotate 来管理日志,linuxlogrotate


大家可能都有管理日志的需要,比如定时压缩日志,或者当日志超过一定大小时就自动分裂成两个文件等。最近就接到这样一个小任务。我们的程序用的是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来保证它会一直开机运行。然后就大工告成了。


linux logrotate管理日志 与cron定期执行

你的配置虽然简单还是正确的
logrotate 是帮助 rotate 日志文件的,可以单独执行, 有一个脚本放在 /etc/cron.daily ,每天被调用来达成自动执行的目的,配置文件的参数可以很多,具体你可以参考现有的 /etc/logrotate.d 下的其他文件 和 man logrotate, 它还需要参考 /var/lib/logrotate.status 里面的最近rotate日期来判断日志文件是否需要rotate
 

linux logrotate 指令管理日志

那个logrotate的任务计划不是后台运行的,他是隔一段时间才起来检查一次,可能需要修改一下配置。上次我也测试过一次,具体忘了
 

相关内容