網上的nginx切割日誌的腳本在運用到每一個不一樣的生產環境中時,老是須要大量更改,還容易出錯,尤爲在處理大量日誌的時候。而且有的腳本自己存在不少問題。所以本人自已作了一些修改,在統一設置變量以後,對日誌目錄的全部.log文件進行切割,切割後的日誌保留三個月(工信部要求)。html
腳本保存爲/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>&1nginx
#!/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