logrotate 删除过期的日志

来源:互联网 发布:网络外卖订餐系统 编辑:程序博客网 时间:2024/05/01 11:27

程序生成的日志文件一般需要定期清理,不然既浪费空间又不便于查看。

linux中有个logrotate的程序可以很方便的配置日志清理规则(可以根据时间,日志文件大小等来进行日志的清理)。

介绍一下几种配置模式…

create 模式:

重命名原先的日志文件,并通知程序重新打开一个日志文件(重启程序,或者发送信号通知应用程序重新打开一个日志文件)。

Logrotate size option: Rotate the log file when file size reaches a specific limitIf you want to rotate a log file (for example, /tmp/output.log) for every 1KB, create the logrotate.conf as shown below.$ cat logrotate.conf/tmp/output.log {        size 1k        create 700 bala bala        rotate 4}This logrotate configuration has following three options:size 1k – logrotate runs only if the filesize is equal to (or greater than) this size.create – rotate the original file and create the new file with specified permission, user and group.rotate – limits the number of log file rotation. So, this would keep only the recent 4 rotated log files.

copytruncate 模式:

复制日志文件中的内容到其他文件中,并将该日志文件的size设置为0。
注意:如果文件不是以APPEND模式打开的,则会出现原先日志文件被复制走的部分内容会变成 \0,而在新写入日之后,文件的size会重新恢复到之前的大小(very bad…),所以 copytruncate 要求文件必须以 APPEND 模式打开。。

Logrotate copytruncate option: Continue to write the log information in the newly created file after rotating the old log file.$ cat logrotate.conf/tmp/output.log {         size 1k         copytruncate         rotate 4}copytruncate instruct logrotate to creates the copy of the original file (i.e rotate the original log file) and truncates the original file to zero byte size. This helps the respective service that belongs to that log file can write to the proper file.

APPEND模式打开就是这样的:

std::ofstream ofs;ofs.open ("test.txt", std::ofstream::out | std::ofstream::app)或者:FILE* logfilelogfile = fopen("abc.log","wa");

这样的缺点就是程序每一次启动时,如果已经存在一个对应的文件,最新的日志就会追加到该文件末尾,而不是清空该日志文件然后再写入。

一个可用的配置如下:

# 配置需要rotate的文件,和 size 等guowe@pc:~/robotwork$ cat /etc/logrotate.d/guowei.log/home/guowei/robotwork/*.log {        rotate 2        size 30k        copytruncate        notifempty        missingok}# 然后配置每个小时 rotate一下( cp /etc/cron.daily/logrotate /etc/cron.hourly/ ):guowei@pc:~/robotwork$ cat /etc/cron.hourly/logrotate #!/bin/sh# Clean non existent log file entries from status filecd /var/lib/logrotatetest -e status || touch statushead -1 status > status.cleansed 's/"//g' status | while read logfile datedo    [ -e "$logfile" ] && echo "\"$logfile\" $date"done >> status.cleanmv status.clean statustest -x /usr/sbin/logrotate || exit 0/usr/sbin/logrotate /etc/logrotate.conf

按照上述配置好后,然后执行一下这个,你就会发现你的日志文件被rotate了:

sudo run-parts /etc/cron.daily  # or cron.hourly

关于 logrotate的使用有人解释的更好:
see link:
http://www.lightxue.com/how-logrotate-works
http://www.thegeekstuff.com/2010/07/logrotate-examples

原创粉丝点击