logrotate是一个日志文件管理工具。用来把旧文件轮转、压缩、删除,并且创建新的日志文件,我们把它叫做“转储”。我们可以根据日志文件的大小、天数等来转储,便于对日志文件管理,一般都是通过cron计划任务来完成的,并且可以发送日志到指定的E-mail。
The logrotate utility is designed to simplify the administration of log files on a system which generates a lot of log files. Logrotate allows for the automatic rotation compression, removal and mailing of log files. Logrotate can be set to handle a log file daily, weekly, monthly or when the log file gets to a certain size.
在Debian或Ubuntu上:
# apt-get install logrotate cron
在Fedora,CentOS或RHEL上:
# yum install logrotate crontabs
logrotate的配置文件是/etc/logrotate.conf,通常不需要对它进行修改。日志文件的轮循设置在独立的配置文件中,它(们)放在/etc/logrotate.d/目录下。
logrotate 的配置文件是 /etc/logrotate.conf。主要参数如下表:
logrotate.conf中的配置语法很简单:
日志文件名的绝对路径(如果有多个用空格隔开) {
需要配置的参数
}
命令参数说明
# logrotate --help
Usage: logrotate [OPTION...] <configfile>
-d, --debug 调试模式,输出调试结果,并不执行。隐式-v参数
-f, --force 强制模式,对所有相关文件进行rotate
-m, --mail=command 发送邮件 (instead of `/bin/mail')
-s, --state=statefile 状态文件,对于运行在不同用户情况下有用
-v, --verbose 显示debug信息
/var/log/nginx/*.log /var/log/tomcat/*log { # 可以指定多个路径
daily # 日志轮询周期,weekly,monthly,yearly
rotate 30 # 保存30天数据,超过的则删除
size +100M # 超过100M时分割,单位K,M,G,优先级高于daily
compress # 切割后压缩,也可以为nocompress
delaycompress # 切割时对上次的日志文件进行压缩
dateext # 日志文件切割时添加日期后缀
missingok # 如果没有日志文件也不报错
notifempty # 日志为空时不进行切换,默认为ifempty
create 640 nginx nginx # 使用该模式创建日志文件
sharedscripts # 所有的文件切割之后只执行一次下面脚本
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}
当配置完成后,可以通过如下方式进行测试。
—– 可直接手动执行
$ logrotate --force /etc/logrotate.d/nginx
—– 显示详细的信息;而且–debug/-d实际上不会操作具体文件(Dry Run)
$ logrotate --debug --verbose --force /etc/logrotate.d/nginx
在 CentOS 中,默认会将日志保存 /var/lib/logrotate.status 文件中,如果需要指定到其它文件,可以通过 -s/–state
参数指定。
/var/log/messages {
rotate 5
weekly
postrotate
/sbin/killall -HUP syslogd
endscript
}
"/var/log/httpd/access.log" /var/log/httpd/error.log {
rotate 5
mail www@my.org
size 100k
sharedscripts
postrotate
/sbin/killall -HUP httpd
endscript
}
/var/log/news/* {
monthly
rotate 2
olddir /var/log/news/old
missingok
postrotate
kill -HUP ‘cat /var/run/inn.pid‘
endscript
nocompress
}