【shell脚本】nginx每天自动切割日志脚本

时间:2023-03-08 16:28:29

nginx每天日志量比较大的时候,最好每天自动切割,存储,这样可以方面以后的查询和分析

#!/bin/sh
###################
#filename: nginx_log_rotate.sh
#vsersion: 0.1v
#1 0 * * * /bin/sh /home/project/monitor/nginx_log_rotate.sh >/dev/null 2>&1
###################

logs_path="/usr/local/openresty/nginx/logs"
old_logs_path=${logs_path}/old
nginx_pid=`cat /usr/local/openresty/nginx/logs/nginx.pid`

time_stamp=`date -d "yesterday" +"%Y-%m-%d"`

mkdir -p ${old_logs_path}

#grep some mode file
for file in `ls $logs_path | grep log$ | grep -v '^20'`
do
    if [ ! -f ${old_logs_path}/${time_stamp}_$file ]
    then
        dst_file="${old_logs_path}/${time_stamp}_$file"
    else
        dst_file="${old_logs_path}/${time_stamp}_$file.$$"
    fi
    mv $logs_path/$file $dst_file
    #gzip -f $dst_file  # do something with access.log.0
done

kill -USR1 $nginx_pid