计划任务 Nginx 日志轮询切割
本环境是基于 Centos 7.8 系统构建Nginx学习环境
具体构建,请参考 Nginx-1.18.0 环境部署
Nginx作为一个非常强大的web服务器、反向代理服务器。部署到线上业务,尤其是线上业务量剧增的网站。Nginx服务器访问量是非常大的,巨大的访问量也带来了,日志文件的增大,尤其是Nginx服务的访问日志。所有我们很有需要有计划的对Nginx访问日志进行日志轮询切割。
Nginx服务yum在线部署,已经自动部署好了日志切割,但是源码方式安装,需要管理员手工设定
一、yum方式的日志轮询切割
查看nginx服务默认的日志切割文件
[root@node01 ~]# vim /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
create 640 nginx adm
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}
二、源码方式的日志轮询切割
1、方法一(配置文件)
logrotate 本身就是以计划任务方式运行
[root@node02 ~]# vim /etc/logrotate.d/nginx
/usr/local/nginx/logs/*.log {
dateext
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 nginx adm
sharedscripts
postrotate
if [ -f /usr/local/nginx/logs/nginx.pid ]; then
kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
fi
endscript
}
测试
[root@node02 ~]# logrotate -f /etc/logrotate.d/nginx
[root@node02 ~]# ll /usr/local/nginx/logs/
total 12
-rw-r----- 1 nginx adm 0 Feb 21 20:44 access_2021-02-21.log
-rw-r--r-- 1 nginx root 0 Feb 21 19:45 access.log
-rw-r----- 1 nginx adm 0 Feb 21 20:44 error.log
-rw-r--r-- 1 root root 620 Feb 21 19:45 error.log-20210221
-rw-r--r-- 1 root root 5 Feb 21 19:31 nginx.pid
2、方法二(服务脚本+计划任务)
提供脚本
[root@node02 ~]# mkdir /scripts
[root@node02 ~]# cd /scripts
[root@node02 scripts]# vim cut_nginx_access_logs.sh
#!/bin/bash
# def var
date_format=$(date +%F)
log_dir=/usr/local/nginx/logs
log_name=access
# main program
[ -d ${log_dir} ] && cd ${log_dir} || exit 1
[ -f ${log_dir}/${log_name}.log ] || exit 1
mv ${log_dir}/${log_name}.log ${log_dir}/${log_name}_${date_format}.log
/usr/local/nginx/sbin/nginx -s reload
[root@node02 scripts]# chmod +x cut_nginx_access_logs.sh
[root@node02 scripts]# sh -n cut_nginx_access_logs.sh
[root@node02 scripts]# ./cut_nginx_access_logs.sh
[root@node02 scripts]# ll /usr/local/nginx/logs/
total 12
-rw-r--r-- 1 root root 614 Feb 21 16:41 access_2021-02-21.log
-rw-r--r-- 1 root root 0 Feb 21 19:45 access.log
-rw-r--r-- 1 root root 620 Feb 21 19:45 error.log
-rw-r--r-- 1 root root 5 Feb 21 19:31 nginx.pid
配置计划任务
[root@node02 scripts]# crontab -e
# cut nginx access logs by wan
00 03 * * * /bin/bash /scripts/cut_nginx_access_logs.sh &> /dev/null