#!/bin/bash
# 文件名: nginx_log_patition.sh
# 功能: nginx 日志分割脚本

### 变量定义 开始 ###

export LOG_PATH=${LOG_PATH:-"/data/logs/access"}                      # Nginx 访问日志目录
export TAR_PATH=${TAR_PATH:-"/data/logs/archiving"}                   # 日志归档根目录
export YESTERDAY=${YESTERDAY:-$(date -d "-1 days" +%Y-%m-%d)}         # 获取昨天日期
export KEEP_DAY=${KEEP_DAY:-$(date -d "-30 days" +%Y-%m-%d)}          # 删除 30天前日志
export NGX_BIN=${NGX_BIN:-"/usr/local/nginx/sbin/nginx"}              # Nginx 二进制文件

### 变量定义 结束 ###

# 创建日志归档目录
[[ -d ${TAR_PATH} ]] || mkdir -p ${TAR_PATH}

# 将日志移动到归档目录
for i in `find ${LOG_PATH} -type f -name '*.log'`
do
	mv -f ${i} ${TAR_PATH}/${YESTERDAY}_${i##*/} &
done
wait

# 重新生成日志
${NGX_BIN} -s reopen

# 压缩并删除源日志
for j in `find ${TAR_PATH} -type f -name '*.log'`
do
	tar cavf ${TAR_PATH}/`basename ${j##*/} .log`.tar.xz ${TAR_PATH}/${j##*/} --remove-files >/dev/null 2>&1
done

# 删除保留期限日志
for x in `find ${TAR_PATH} -type f -name "*${KEEP_DAY}*"`
do
	rm -f $x
done
