nginx切割日誌

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

腳本保存爲/root/sh/nginx_cut_log.shbash

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

而後在/etc/crontab中添加:crontab

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

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

# 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
export LC_ALL=C
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bindate

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

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
figrep

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" ];thenrm -rf "$delmonth"echo "`date` Delete ${logs_bakpath}/${delyear}/${delmonth}"elseecho "`date` Not deleted."fi

相關文章
相關標籤/搜索