Nginx日志切割

Nginx自带没有日志轮循功能,需要借助系统logrotate或自写脚本实现,下面是使用脚本来实现:

#!/bin/bash
# Author:Chris                          __On 2016/10/28
# =====================Description=====================
# [Features]: Nginx logrotate & Backup Logs.
# [Usage]: Add a scheduled task:
#          0 0 * * * /root/Scripts/logrotate_nginx.sh
# =====================================================

# Defined Color
Red='\033[31m\033[1m'	# \e[1;31m
Green='\033[32m\033[1m'	# \e[1;32m
Blue='\033[94m'		# \e[0;94m
Null='\033[0m'		# \e[0m

# <----------------------------Configure Start--------------------------->
Logdir="/data/nginx/logs"
Bakdir="/data/backup/logs/nginx"
Pidfile="/data/nginx/logs/nginx.pid"
Pid=$(cat ${Pidfile})
Date=$(date -d yesterday +%Y-%m-%d)
Rather=8192
# <----------------------------Configure  End---------------------------->

Checkdo (){
    if [ "$?" -ne 0 ];then
		echo -n .
		echo -e "[ ${Red}NO${Null} ]"
		echo -e "${Red}Execte Faild.${Null}"
		exit 1
    fi
    echo -n .
    echo -e "[ ${Green}OK${Null} ]"
}

echo -e Starting Nginx logrotate in dir: ${Blue}${Logdir}${Null}...
echo -n 1.Detect Directory..
if [ ! -d ${Logdir} ];then
    echo -n .
    echo -e "[ ${Red}NO${Null} ]"
    echo -e "${Red}Log directory ${Logdir} is not exist.${Null}"
    exit 1
fi
if [ ! -d ${Bakdir} ];then
    mkdir -p ${Bakdir}
fi
echo -n .
echo -e "[ ${Green}OK${Null} ]"

# Rotate Log.
echo -n 2.Rotating log..
cd ${Logdir}
ls -l | grep -E .log$ \
| while read line
do
    fsize=$(echo $line | awk '{print $5}')
    fname=$(echo $line | awk '{print $NF}')
    lname=${Date}-${fname}
    if [ "${fsize}" -lt "${Rather}" ];then
		continue
    fi
    mv ${fname} ${Bakdir}/${lname}
done
Checkdo

# Send USR1 signal to Nginx.
echo -n 3.Send USR1 singal to Nginx..
kill -USR1 ${Pid} > /dev/null 2>&1
Checkdo

# Compress log files.
echo -n 4.Compressing log files..
cd ${Bakdir}
tar czf ${Date}.tar.gz ${Date}-* --remove-files
Checkdo

echo -e "${Green}Logrorate Complated!${Null}"

思路:将日志文件移动出来,然后给Nginx发出USR1指令(因为Nginx是按文件的inode来写入日志的)。

发表评论

error: Content is protected !!