Nginx 是一个非常轻量的 Web 服务器,体积小、性能高、速度快等诸多优点。但不足的是也存在缺点,比如其产生的访问日志文件一直就是一个,如果是yum方式安装的nginx,系统默认会自动通过logrotate这个日志管理软件,按天进行分割。而如果是源码编译方式安装nginx其日志不会自动地进行切割,如果访问量很大的话,将导致日志文件容量非常大,不便于管理。当然了,我们也不希望看到这么庞大的一个访问日志文件,那需要手动对这个文件进行切割。
Shell 脚本
[root@VM-0-2-centos logs]# cd ..
[root@VM-0-2-centos nginx]# cat cut_del_nginx_logs.sh
#!/bin/bash
source /etc/profile
#define variables
logs_path="/nginx/logs/"
yesterday_date="`date -d 'yesterday' +%Y-%m-%d`"
today_date="`date +%Y-%m-%d`"
special_day_date="`date -d '60 day ago' +%Y-%m-%d`"
#logrotate by day
mv ${logs_path}/access.log ${logs_path}/access.${yesterday_date}.log
#向nginx主进程发送USR1信号,重新打开日志文件,否则会继续往mv后的文件写数据的。
#原因在于:linux系统中,内核是根据文件描述符来找文件的。如果不这样操作导致日志切割失败。
kill -USR1 `ps axu | grep "nginx: master process" | grep -v grep | awk '{print $2}'`
#删除60天前的日志
if [ -d ${logs_path}/access.${special_day_date}.log ];
then
rm -rf ${logs_path}/access.${special_day_date}.log
else
echo "$special_day_date这天没有日志"
fi
[root@VM-0-2-centos nginx]#
该shell脚本有两个功能,第一个是切割nginx日志,第二个是删除60天前的nginx日志。
在切割nginx日志的功能中,我们要注意该shell脚本命名切割的日志是以前一天的时间命名该日志文件的。
所以我们在把该shell脚本放在crontab中执行时,建议在每天的0点0分执行。如下:
编写定时任务
[root@VM-0-2-centos nginx]#
[root@VM-0-2-centos nginx]# crontab -l
*/5 * * * * flock -xn /tmp/stargate.lock -c '/usr/local/qcloud/stargate/admin/start.sh > /dev/null 2>&1 &'
00 00 * * * root /nginx/cut_del_nginx_logs.sh
[root@VM-0-2-centos nginx]#
[root@VM-0-2-centos nginx]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
[root@VM-0-2-centos nginx]#
参考文章:https://blog.csdn.net/yuki5233/article/details/89489015
2 条评论
看不懂,好厉害的样子
这个是服务器那边用的,你们用了宝塔面板的话,应该是不需要的。我这边是编译安装的,所以日志部分只能自己来控制。