【Nginx】日志切割和定期删除日志

本文日志切割和定期删除日志都是通过定时任务(cron)执行脚本完成

日志切割脚本

cut_nginx_log_of_yesterday.sh

#!/bin/bash
# program:
#       cut nginx log of yesterday
source /etc/profile

log_path="/data/logs/nginx/"
yesterday=$(date -d "yesterday" +"%Y%m%d")

mv ${log_path}error.log ${log_path}error.$yesterday.log
mv ${log_path}pc_access.log ${log_path}pc_access.$yesterday.log

nginx -s reload

定期删除脚本

rm_nginx_log.sh

#!/bin/bash
#program:
#       delete nginx logs of 10 days ago
find /data/logs/nginx/ -mtime +10 -name "*.log" -exec rm -rf {} \;

cron 配置文件

cron.conf 配置以上两个脚本到定时任务

0 0 * * * /bin/bash /opt/script/cut_nginx_log/cut_nginx_log_of_yesterday.sh
0 16 * * * /bin/bash /opt/script/cut_nginx_log/rm_nginx_log.sh

脚本上传Nginx服务器并添加定时任务

本地编写脚本add.sh,把cut_nginx_log_of_yesterday.sh、rm_nginx_log.sh和cron.conf上传到Nginx服务器,并添加定时任务

#!/bin/bash
#program:
#       add cron to cut nginx log on nginx server

ip_array=(192.168.1.1 192.168.1.2 192.168.1.3)

cron_conf_from_path="/data/scripts/cron_to_cut_nginx/"
cron_script_from_path="/data/scripts/cron_to_cut_nginx/"

cron_conf_to_path="/opt/conf/cron_to_cut_nginx_log/"
cron_script_to_path="/opt/script/cut_nginx_log/"

for ip in ${ip_array[@]}
do
        ssh root@${ip} "mkdir -p ${cron_conf_to_path}"
        scp ${cron_conf_from_path}cron.conf root@${ip}:${cron_conf_to_path}cron.conf

        ssh root@${ip} "mkdir -p ${cron_script_to_path}"
        scp ${cron_script_from_path}cut_nginx_log_of_yesterday.sh root@${ip}:${cron_script_to_path}cut_nginx_log_of_yesterday.sh
        scp ${cron_script_from_path}rm_nginx_log.sh root@${ip}:${cron_script_to_path}rm_nginx_log.sh
        ssh root@${ip} "crontab ${cron_conf_to_path}cron.conf"
        echo "${ip}"
        ssh root@${ip} "crontab -l"

done

最后本地执行 sh add.sh就把前面的脚本上传到了nginx服务器上,并且加入了cron定时任务

你可能感兴趣的:(Nginx)