logrotate日志分割

By | 2013-10-11

/etc/logrotate.d/目录存在各种服务:如squid、nginx、httpd等

# less /etc/logrotate.d/squid    
/web/squid/logs/access.log /web/squid/logs/cache.log /web/squid/logs/store.log {  
    daily  
    missingok  
    nocompress  
    noolddir  
    sharedscripts  
    postrotate  
DATE=`/bin/date--date=yesterday +%y%m%d` 
        LOGDIR="/web/squid/logs"
        /usr/sbin/squid -k rotate 2>/dev/null || true
        sleep 10  
for LOGFILE in ${LOGDIR}/*.log; do  
          [ -f ${LOGFILE}.1 ] && mv ${LOGFILE}.1 ${LOGFILE}-${DATE}  
          [ -f ${LOGFILE}-${DATE} ] && /bin/gzip ${LOGFILE}-${DATE}  
        done  
        /usr/bin/find ${LOGDIR}/ -type f -name"*.log-*.gz" -mtime +180 -exec rm -f {} \;  
    endscript  
} 

该脚本执行logrotate命令:

# cat /etc/cron.daily/logrotate  
#!/bin/sh  
/usr/sbin/logrotate /etc/logrotate.conf  
EXITVALUE=$?  
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi  
exit 0 

conf配置文件,注意include选项

# cat /etc/logrotate.conf
# RPM packages drop log rotation information into this directory
include /etc/logrotate.d

查看/etc/crontab文件,这是crontab的默认参数

# cat /etc/crontab  
SHELL=/bin/bash  
PATH=/sbin:/bin:/usr/sbin:/usr/bin  
MAILTO=root  
HOME=/  
# run-parts  
01 * * * * root run-parts /etc/cron.hourly  
02 4 * * * root run-parts /etc/cron.daily  
22 4 * * 0 root run-parts /etc/cron.weekly  
42 4 1 * * root run-parts /etc/cron.monthly 

run-parts /etc/cron.daily 执行命令执行了改目录下的所有脚本,如下:

# ls /etc/cron.daily/
0logwatch  cups  logrotate  makewhatis.cron  mlocate.cron  prelink  rpm  tmpwatch

这个流程是,cron 负责调度,crond 读 /etc/crontab 获得配置, /etc/crontab 包含 /etc/cron.daily 目录下的所有配置,而 logrotate 则是其中的一个任务;logrotate 每天 4 点 2 分开始跑,logrotate 又读自己的配置 /etc/logrotate.conf,logrotate.conf 包含 /etc/logrotate.d 下的配置,squid 是其中的一个。

为了避免重复操作,logrotate 会记一个状态在 /var/lib/logrotate.status 文件中,故/usr/sbin/logrotate /etc/logrotate.conf 命令一直无效,-f参数强制执行会覆盖已有的数据

Leave a Reply

Your email address will not be published. Required fields are marked *