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
#2011         soonyo   create
#2013/01/17   zhaoyn   Improve
#2013/02/22   zhaoyn   Improve
#2013/05/27   zhaoyn   compress the log
# 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 " 4 months ago"  +"%m")
deldays=90
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
   gzip "$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` Did not delete the directory."
fi
if [ -d "$logs_bakpath" ]; then
    cd $logs_bakpath
    echo "`date` Deletes the file list."
    find $logs_bakpath -maxdepth 3 -type f -name "*.log" -mtime +"$deldays"
    find $logs_bakpath -maxdepth 3 -type f -name "*.log" -mtime +"$deldays" | xargs rm -rf
    find $logs_bakpath -maxdepth 3 -type f -name "*.log.gz" -mtime +"$deldays"
    find $logs_bakpath -maxdepth 3 -type f -name "*.log.gz" -mtime +"$deldays" | xargs rm -rf
else
    echo "`date` Log directory does not exist, exit."
    exit
fi


原文:http://www.zhaoyanan.cn/nginx-log-cut.html


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章