logrotate 用于切割日志非常方便。
logrotate 是基于 crontab 实现的。无需守护进程。
安装完定时任务配置在 /etc/crontab.daily/logrotate 文件中,crontab 服务启动的情况下每天会执行一次。
具体 daily 目录的执行时间 CentOS 下在 /etc/anacrontab 中设置
logrotate 的默认操作方式是 mv + create,执行成本非常低,需要应用支持自动打开新文件写,常见的新软件都支持这种方式。
无注释版本
/var/log/nginx/*/*.log {
create 0644 nginx nginx
daily
rotate 10
missingok
notifempty
compress
delaycompress
size=1000M
dateext
sharedscripts
postrotate
/bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
endscript
}
意义注释
/var/log/nginx/*/*.log { //nginx 日志下按 vhost 分目录配置了不同项目的日志
create 0644 nginx nginx //nginx 日志所属用户的权限
daily//默认会继承/etc/logrorate.conf的全局变量,是weekly
rotate 10 //切割日志最大保留数量,一般存储容量够的话建议保留 15 天以上
missingok
notifempty
compress //是否通过gzip压缩转储以后的日志文件,如xxx.log-20131216.gz ;如果不需要压缩,注释掉就行
delaycompress //延迟压缩
size=1000M //大小到达size开始转存
dateext //这个参数很重要!就是切割后的日志文件以当前日期为格式结尾,如xxx.log-20131216这样,如果注释掉,切割出来是按数字递增,即前面说的 xxx.log-1这种格式
sharedscripts
postrotate
/bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
endscript
}
由于 MySQL 的特殊性,需要切割日志后清理日志,最佳实践参考此文Rotating MySQL Slow Logs Safelyengineering.groupon.com
/var/mysql/slow_query.log {
nocompress
create 660 mysql mysql
size 1G
dateext
missingok
notifempty
sharedscripts
postrotate
/usr/local/bin/mysql -e 'select @@global.long_query_time into @lqt_save; set global long_query_time=2000; select sleep(2); FLUSH LOGS; select sleep(2); set global long_query_time=@lqt_save;'
endscript
rotate 150
}
php-fpm日志切割
/var/log/php-fpm/*log {
missingok
notifempty
delaycompress
sharedscripts
postrotate
kill -SIGUSR1 `cat /var/run/php-fpm/php-fpm.pid 2>/dev/null` 2>/dev/null || true
endscript
}