第一步:配置logrotate执行周期
把logrotate从目录/etc/cron.daily拷贝到目录/etc/cron.hourly
脚本logrotate的内容如下:
#!/bin/sh
/usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
/usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0
logrotate的原理就是一个cron job;当时间到了以后,触发执行对应脚本;缺省情况下是一个按天脚本,每天执行一下。
第二步:定义每小时的执行内容。
创建一个自定义脚本,放在目录/etc/logrotate.d下面(这个目录下面的脚本自动由/etc/logrotate.conf指定加载),例如:
$ cat /etc/logrotate.d/mylog
/u01/logs/*.log
{
hourly
dateext
create 0644
missingok
notifempty
maxsize 10M
rotate 168
postrotate
/bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
endscript
}
几个主要参数:
- hourly 表明每小时认为,必须配置
这个地方注意,我们在第一步的时候把logrotate拷贝到了/etc/cron.hourly,那么既然在这里指定了hourly,是不是可以省略第一步的操作呢?答案是不行的,因为放在/etc/cron.daily下面的任务每天才触发一次,它每次触发会读取/etc/logrotate.d/mylog配置,虽然它识别出这里配置了hourly,但是调用者本身每天才调用一次。 - dateext备份的文件自动加日前扩展,因为我们的例子中是按小时的,那么这个扩展日前也是到小时为止;例如:
/u01/logs/aa.log-2020013110 # 2020-01-31_10
/u01/logs/aa.log-2020013111 # 2020-01-31_11
/u01/logs/aa.log-2020013112 # 2020-01-31_12
/u01/logs/aa.log-2020013113 # 2020-01-31_13
/u01/logs/aa.log-2020013114 # 2020-01-31_14
/u01/logs/aa.log # current log
- rotate保持7天=24*7=168
网友评论