使用linux系统自带的Logrotate分割&切割lighttpd日志


最近搭建的静态资源服务器使用的是lighttpd,每天要产生上百M的access.log日志文件,如何对日志按天进行分割呢?

常规的办法是自己写一个脚本,然后添加cron任务,或者使用第三方的工具定时切割日志文件。

但是,linux已经给大家提供了一个日志管理软件Logrotate,其实功能很强大、配置也很简单,不过好像大部分人都喜欢折腾,完全忽视了它的存在。

Logrotate是基于CRON来运行的,其脚本位于/etc/cron.daily/logrotate
#!/bin/sh
/usr/sbin/logrotate /etc/logrotate.conf >/dev/null 2>&1
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
/usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0
[root@baidu-bj-dl-1 logrotate.d]# cat /etc/cron.daily/logrotate
#!/bin/sh
/usr/sbin/logrotate /etc/logrotate.conf >/dev/null 2>&1
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
/usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0
如何使用Logrotate呢?
运行时,Logrotate会调用配置文件/etc/logrotate.conf
缺省配置如下:
# see "man logrotate" for details
# rotate log files weekly
weekly
# keep 4 weeks worth of backlogs
rotate 4
# create new (empty) log files after rotating old ones
create
# uncomment this if you want your log files compressed
#compress
# RPM packages drop log rotation information into this directory
include /etc/logrotate.d
# no packages own wtmp -- we'll rotate them here
/var/log/wtmp {
monthly
minsize 1M
create 0664 root utmp
rotate 1
}
# system-specific logs may be also be configured here.
但是需要日志的服务在安装时已经在/etc/logrotate.d中添加了各自的配置文件,我们只需要修改相应的配置文件即可获得想要的日志功能,相关的配置参数说明如下:
monthly: 日志文件将按月轮循。其它可用值为‘daily’,‘weekly’或者‘yearly’。
dateext 切换后的日志文件会附加上一个短横线和YYYYMMDD格式的日期,没有这个配置项会附加一个小数点加一个数字序号。
rotate 5: 一次将存储5个归档日志。对于第六个归档,时间最久的归档将被删除。
compress: 在轮循任务完成后,已轮循的归档将使用gzip进行压缩。
delaycompress: 总是与compress选项一起用,delaycompress选项指示logrotate不要将最近的归档压缩,压缩将在下一次轮循周期进行。这在你或任何软件仍然需要读取最新归档时很有用。
missingok: 在日志轮循期间,任何错误将被忽略,例如“文件无法找到”之类的错误。
notifempty: 如果日志文件为空,轮循不会进行。
copytruncate 在复制当前日志文件后,将日志文件清空;而不是将当前日志文件改名后创建一个新的。
create 644 root root: 以指定的权限创建全新的日志文件,同时logrotate也会重命名原始日志文件。
postrotate/endscript: 在所有其它指令完成后,postrotate和endscript里面指定的命令将被执行。在这种情况下,rsyslogd 进程将立即再次读取其配置并继续运行。
配置示例
例如,默认的lighttpd日志管理配置文件/etc/logrotate.d/lighttpd中的配置如下:
/var/log/lighttpd/*log {
missingok
notifempty
sharedscripts
postrotate
/usr/bin/killall -HUP lighttpd &>/dev/null || :
endscript
}
我们修改一下,按天保存一周的lighttpd文件并压缩配置文件修改为:
/var/log/lighttpd/*log {
daily
dateext
rotate 7
compress
delaycompress
missingok
notifempty
create 644 root root
sharedscripts
postrotate
/usr/bin/killall -HUP lighttpd &>/dev/null || :
endscript
}
Debug一下,看看配置有无问题
logrotate -d -f /etc/logrotate.d/lighttpd
立即切割今天的日志
logrotate -f /etc/logrotate.d/lighttpd