Nginx切割日志目录所有日志的脚本

网上的nginx切割日志的脚本在运用到每个不同的生产环境中时,总是需要大量更改,还容易出错,尤其在处理大量日志的时候。并且有的脚本本身存在很多问题。因此本人自已做了一些修改,在统一设置变量之后,对日志目录的所有.log文件进行切割,切割后的日志保留三个月。

脚本保存为/root/sh/nginx_cut_log.sh

chmod u+x /root/sh/nginx_cut_log.sh

然后在/etc/crontab中添加:

00 0 * * *  root /root/sh/nginx_cut_log.sh >> /root/sh/nginx_cut_log.log 2>&1

#!/bin/bash
#History
######################################################
#update author
#2013/01/17 zhaoyn Improve

# 00 0 * * * root /root/sh/nginx_cut_log.sh >> /root/sh/nginx_cut_log.log 2>&1
########## variable #######################################
nginx_dir=/opt/nginx
nginx_log_dir=/opt/nginx/logs
logs_bakpath=/var/log/nginx
year=$(date -d "yesterday" +"%Y")
month=$(date -d "yesterday" +"%m")
delyear=$(date -d "3 months ago" +"%Y")
delmonth=$(date -d " 3 months ago" +"%m")
cut_log_path=${logs_bakpath}/${year}/${month}

export LANG=C
export LC_ALL=C
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

####### do ##############################################
if [ ! -d "$cut_log_path" ];then
mkdir -p ${logs_bakpath}/${year}/${month}
fi

echo ""
echo ""
echo "`date` start."
echo "##################################"
#### move yesterday logs ####
echo "`date` move yesterday logs."
if [ -d "$nginx_log_dir" ]; then
cd $nginx_log_dir
ls | grep ".log" | awk -F '.log''{print $1}' > /tmp/nginxloglist.txt
else
echo "log backup directory does not exist, exit"
exit 1
fi

for logfilename in `cat /tmp/nginxloglist.txt`
do
mv "$logfilename".log "$cut_log_path"/"$logfilename"_$(date -d "yesterday" +"%Y%m%d").log
done

#### nginx reopen log ####
kill -USR1 `cat ${nginx_dir}/logs/nginx.pid`
#or
#${nginx_dir}/sbin/nginx -s reopen

#### Delete 3 months before the log ####
cd "$logs_bakpath"/"$delyear"
if [ -d "$delmonth" ];then
rm -rf "$delmonth"
echo "`date` Delete ${logs_bakpath}/${delyear}/${delmonth}"
else
echo "`date` Not deleted."
fi

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/e1c481abfff08257243ee97b95ceb4a8.html