Logrotate-Problem

今天遇到一个logrotate的问题。

现象是配置不生效(其实也不是完全不生效,只是每小时的滚转策略变成一天了)。

配置文件:

# 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

# use date as a suffix of the rotated file
dateext

# uncomment this if you want your log files compressed
#compress

# packages drop log rotation information into this directory
include /etc/logrotate.d
$ ls -l /etc/cron.hourly/*
-rwxr-xr-x 1 root root 372 Mar 22  2017 /etc/cron.hourly/logrotate

$ cat /etc/cron.hourly/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

对于syslog的配置:

/var/log/messages
{
	rotate 4
	hourly
	size 100M
	missingok
	notifempty
	compress
	delaycompress
	sharedscripts
	postrotate
		/bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
	endscript
}

手动执行logrotate的时候,如果当前没有滚转的日志,那么是可以创建一个滚转文件的:

$ ls -lh mess*
-rw------- 1 root root  155 Jan  8 05:10 messages
-rw------- 1 root root 6.3M Jan  8 05:10 messages-20180108.gz

但再次将messages写过100M,运行logrotate就不正常了,不能创建新的压缩文件。

debug日志:

...
...
rotating pattern: /var/log/messages
 104857600 bytes (3 rotations)
empty log files are rotated, old logs are removed
considering log /var/log/messages
  log needs rotating
rotating log /var/log/messages, log->rotateCount is 3
dateext suffix '-20180108'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
destination /var/log/messages-20180108.gz already exists, skipping rotation
...
...

说是已经有一个这样的文件存在了,跳过滚转。

所以如果删掉这个文件,或者这个文件不存在的话,就会生效。那么是什么导致创建这样一个文件呢?

答案在这一行

# use date as a suffix of the rotated file
dateext

如果没有注释掉这一行的话,新产生的rotate文件就会以时间命名,默认是具体到天,所以执行每小时的滚转的时候,就会跳过,因为已经创建了这样一个文件了。

解决的办法是,可以将此行注释,这样生成的滚转文件就会用123来计数命名;也可以更改这个格式,添加下面一行到config文件:

dateformat -%Y-%m-%d-%s

其实去掉dateext就可以,毕竟文件创建也有时间戳:

$ ls -lh mess*
-rw------- 1 root root  155 Jan  8 05:10 messages
-rw------- 1 root root 5.9M Jan  8 05:11 messages.1.gz
-rw------- 1 root root 6.3M Jan  8 05:10 messages.2.gz
$
comments powered by Disqus