样例三
我们想要让旧日志文件以创建日期命名,这可以通过添加dateext常熟实现。
- # vim /etc/logrotate.d/log-file
- /var/log/log-file {
- monthly
- rotate 5
- dateext
- create 644 root root
- postrotate
- /usr/bin/killall -HUP rsyslogd
- endscript
- }
这将让归档文件在它们的文件名中包含日期信息。
排障
这里提供了一些logrotate设置的排障提示。
1. 手动运行logrotate
logrotate可以在任何时候从命令行手动调用。
要调用为/etc/lograte.d/下配置的所有日志调用logrotate:
- # logrotate /etc/logrotate.conf
要为某个特定的配置调用logrotate:
- # logrotate /etc/logrotate.d/log-file
2. 演练
排障过程中的最佳选择是使用‘-d’选项以预演方式运行logrotate。要进行验证,不用实际轮循任何日志文件,可以模拟演练日志轮循并显示其输出。
- # logrotate -d /etc/logrotate.d/log-file

正如我们从上面的输出结果可以看到的,logrotate判断该轮循是不必要的。如果文件的时间小于一天,这就会发生了。
3. 强制轮循
即使轮循条件没有满足,我们也可以通过使用‘-f’选项来强制logrotate轮循日志文件,‘-v’参数提供了详细的输出。
- # logrotate -vf /etc/logrotate.d/log-file
- reading config file /etc/logrotate.d/log-file
- reading config info for/var/log/log-file
- Handling1 logs
- rotating pattern:/var/log/log-file forced from command line (5 rotations)
- empty log files are rotated, old logs are removed
- considering log /var/log/log-file
- log needs rotating
- rotating log /var/log/log-file, log->rotateCount is5
- dateext suffix '-20140916'
- glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
- renaming /var/log/log-file.5.gz to /var/log/log-file.6.gz(rotatecount 5, logstart 1, i 5),
- old log /var/log/log-file.5.gz does not exist
- renaming /var/log/log-file.4.gz to /var/log/log-file.5.gz(rotatecount 5, logstart 1, i 4),
- old log /var/log/log-file.4.gz does not exist
- ...
- renaming /var/log/log-file.0.gz to /var/log/log-file.1.gz(rotatecount 5, logstart 1, i 0),
- old log /var/log/log-file.0.gz does not exist
- log /var/log/log-file.6.gz doesn't exist -- won't try to dispose of it
- renaming /var/log/log-file to /var/log/log-file.1
- creating new/var/log/log-file mode =0644 uid =0 gid =0
- running postrotate script
- compressing log with:/bin/gzip
4. Logrotate的记录日志
logrotate自身的日志通常存放于/var/lib/logrotate/status目录。如果处于排障目的,我们想要logrotate记录到任何指定的文件,我们可以指定像下面这样从命令行指定。
- # logrotate -vf –s /var/log/logrotate-status /etc/logrotate.d/log-file
5. Logrotate定时任务
logrotate需要的cron任务应该在安装时就自动创建了,我把cron文件的内容贴出来,以供大家参考。
- # cat /etc/cron.daily/logrotate
- #!/bin/sh
- # Clean non existent log file entries from status file
- cd /var/lib/logrotate
- test -e status || touch status
- head -1 status > status.clean
- sed 's/"//g' status |while read logfile date
- do
- [-e "$logfile"]&& echo "\"$logfile\" $date"
- done>> status.clean
- mv status.clean status
- test -x /usr/sbin/logrotate ||exit0
- /usr/sbin/logrotate /etc/logrotate.conf
小结一下,logrotate工具对于防止因庞大的日志文件而耗尽存储空间是十分有用的。配置完毕后,进程是全自动的,可以长时间在不需要人为干预下运行。本教程重点关注几个使用logrotate的几个基本样例,你也可以定制它以满足你的需求。
希望本文对你有所帮助。
本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-10/108725.htm
