Nginx日志滚动可分为3步:
- 将access.log重命名成形如access_202006161113.log
- 通过kill命令向nginx的进程发送 -USR1信号,通知nginx重新创建access.log文件
- 删除修改时间比指定时间更早的历史日志
示例脚本:
#!/bin/bash
# rename access.log
NGINX_LOG_HOME="/data/web_log/nginx"
minu=`date "+%Y%m%d%H%M"`
src=$NGINX_LOG_HOME/access.log
dst=$NGINX_LOG_HOME/access_$minu.log
mv $src $dst
# notify nginx reopen a new access.log
nginx_pid=/var/run/nginx.pid
kill -USR1 `cat $nginx_pid`
# remove outdated log files
cd $NGINX_LOG_HOME
nginx_backup_minutes=1440 # 1440分钟,即24小时
find . -type f -name "*.log" -mmin +${nginx_backup_minutes} | xargs rm -f
脚本的调用一般配在crontab里,例如:
0 * * * * /bin/bash /usr/local/logrotate_nginx.sh