驽马十驾

驽马十驾,功在不舍

目录
Docker环境下的Nginx每日切割文件
/    

Docker环境下的Nginx每日切割文件

核心脚本如下:

YEAR=$(date +%Y)
R=$(date +%Y)
MONTH=$(date +%m)
DAY=$(date +%d)
YESTERDAY=$(date -d "yesterday" +%Y-%m-%d)
# 只需修改此处
FOLDER=ubirth-api

# 日志的原始路径
LOGS_PATH=/ubirth-proc/docker-data/nginx/logs/${FOLDER}
# 日志的备份路径
LOGS_BAK_PATH=/ubirth-proc/logs/nginx/${FOLDER}

# 得到1级目录名
if [[ $(($DAY)) -eq 1 ]]
  then
    if [[ $(($MONTH)) -eq 1 ]]
      then
        LOGS_BAK_PATH=$LOGS_BAK_PATH/$((${YEAR}-1))-12
        echo 1
    else
      if [[ $(($MONTH)) -gt 10 ]]
        then
          LOGS_BAK_PATH=$LOGS_BAK_PATH/${YEAR}-$((${MONTH}-1))
          echo 2
      else
          LOGS_BAK_PATH=$LOGS_BAK_PATH/${YEAR}-0$((${MONTH}-1))
          echo 3
      fi
    fi
else
    LOGS_BAK_PATH=$LOGS_BAK_PATH/${YEAR}-${MONTH}
    echo 4
fi

# 创建目录
mkdir -p $LOGS_BAK_PATH/${YESTERDAY}

# 复制当前的日志文件到备份的目录
cp ${LOGS_PATH}/access.log ${LOGS_BAK_PATH}/${YESTERDAY}/access_${YESTERDAY}.log
> ${LOGS_PATH}/access.log

# admin_log 如果存在才继续操作
admin_log=${LOGS_PATH}/admin_access.log
if [ -x $admin_log ]
then
  cp $admin_log ${LOGS_BAK_PATH}/${YESTERDAY}/admin_access_${YESTERDAY}.log
  > $admin_log
fi

# error_log 如果存在,才继续操作
error_log=${LOGS_PATH}/error.log
if [ -x $error_log ]
then
  cp ${error_log} ${LOGS_BAK_PATH}/${YESTERDAY}/error_${YESTERDAY}.log
  > ${error_log}
fi

# 处理下nginx的日志,避免出现不打日志的问题
docker exec nginx nginx -s reopen

进行定时任务

# 先授权
chmod 777 /xxx.sh
# 然后编辑crontab
vi /etc/crontab
# 每天0:00执行该脚本
0 0 * * * root bash /opt/sh/cutlogs.sh
# 重启
systemctl restart crond

结束

Over。。。建议执行前自行尝试运行下

积土成山,风雨兴焉。积水成渊,蛟龙生焉。
评论