设置nginx日志滚动

时间:2022-06-29 07:06:01

需求:设置nginx每天凌晨12点轮转,系统版本为debian7,nginx版本为tengine2.2.0

1、修改logrotate主配置文件,打开压缩和以时间为后缀命名

# vim /etc/logrotate.conf
# 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 # no packages own wtmp, or btmp -- we'll rotate them here
/var/log/wtmp {
missingok
monthly
create 0664 root utmp
rotate 1
} /var/log/btmp {
missingok
monthly
create 0660 root utmp
rotate 1
} # system-specific logs may be configured here

2、添加一条nginx的logrotate配置(正常配置到这里就可以了)

# vim /etc/logrotate.d/nginx
/usr/local/nginx/logs/*.log {
daily
rotate 7
compress
missingok
sharedscripts
postrotate
if [ -f /usr/local/nginx/sbin/nginx-tengine.pid ]; then
kill -USR1 `cat /usr/local/nginx/sbin/nginx-tengine.pid`
fi
endscript
}

3、删除系统自带的每日轮转任务

# mv /etc/cron.daily/logrotate /tmp/

4、添加一条计划任务,每天凌晨12点轮转

# crontab -e
0 0 * * * /usr/sbin/logrotate /etc/logrotate.conf

5、修改crontab时区,避免时区问题

# vim /etc/crontab
CRON_TZ=Asia/Shanghai # /etc/init.d/cron restart