logrotate实现nginx日志自动切割

使用 Logrorate 切割 nginx 日志

1
vim /etc/logrotate.d/nginx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/var/log/nginx/*.log         												#此处为nginx存储日志的地方;
{
daily #指定转储周期为每天
rotate 30 #转储次数,超过将会删除最老的那一个
missingok #如果日志文件丢失,不要显示错误
compress #通过gzip 压缩转储以后的日志
delaycompress #当前转储的日志文件到下一次转储时才压缩
notifempty #当日志文件为空时,不进行轮转
create 755 nginx adm #创建 775权限、用户组为nginx的日志文件
postrotate #表示当切割之后要执行的命令
if [ -f /var/run/nginx/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx/nginx.pid` #PID路径根据实际路径填写;
fi
endscript
}

测试程序执行的情况

1
logrotate -vf /etc/logrotate.d/nginx

查看 log 文件的具体执行情况

1
cat /var/lib/logrotate/logrotate.status

加入定时任务

1
crontab -e
1
0 0 * * * /usr/sbin/logrotate -vf /etc/logrotate.d/nginx #每天凌晨00:00自动执行日志切割任务;

常见问题

1、分割日志时报错:error: skipping “/var/log/nginx/test.access.log” because parent directory has insecure permissions (It’s world writable or writable by group which is not “root”) Set “su” directive in config file to tell logrotate which user/group should be used for rotation.

在配置文件中添加 “su root nginx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/var/log/nginx/*.log
{
su root list
daily
rotate 30
missingok
compress
delaycompress
notifempty
create 755 nginx adm
postrotate
if [ -f /var/run/nginx/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx/nginx.pid`
fi
endscript
}