#!/bin/bash
set -e                         #当脚本有错误时,便停止执行脚本
LOG_PATH="/var/log/nginx"      #定义日志存放路径
ACCESS_LOG="access.log"
ERROR_LOG="error.log"
YESTERDAY=$(date -d '1 day ago' +%F)        #定义昨天的日期
for i in $(find ${LOG_PATH} -name ${ACCESS_LOG});do
    cd $(dirname ${i})
    if  [[ -f ${ACCESS_LOG} ]];then
        cp {,${YESTERDAY}-}${ACCESS_LOG}         #将原本的日志文件复制一份
        : > ${ACCESS_LOG}                        #将原本的日志内容清空
    fi
    if  [[ -f ${ERROR_LOG} ]];then
        ERROR_SIZE=$(ls -l   ${ERROR_LOG} | awk '{print $5}')
        if  [[ ${ERROR_SIZE} -gt 20971520 ]];then               #如果error.log日志大于20M,进行切割
            cp {,${YESTERDAY}-}${ERROR_LOG}
            : > ${ERROR_LOG}
        fi
    fi
done
find ${LOG_PATH} -type f -name "*.log" -mtime +7 -delete            #将一周前的日志进行删除