nginx日志自动按日期切割保存七天内容 shell

nginx日志自动按日期切割保存七天内容

#!/bin/sh
#Command:/usr/nginx/nginx/tools/clearNginxLog.sh
#Execute time: 00:00:00
LOGS_PATH=/usr/local/webserver/nginx/logs
#nginx pid path
PID=/usr/local/webserver/nginx/logs/nginx.pid

#nginx logs save days
SAVE_DAYS=7

#backup data format
TODAY=$(date -d 'today' +%Y-%m-%d)
CURRENTTIME=$(date -d 'today' +%Y-%m-%d-%H-%M-%S)

logfile=$LOGS_PATH/clearNginxLog_${TODAY}.log

echo "`date +%Y-%m-%d` `date +%H-%M-%S` Start run the shell $0." >> ${logfile}
echo "Security check start." >> ${logfile}
if [ $LOGS_PATH == "/" ] || [ $LOGS_PATH == "/etc" ] || [ $LOGS_PATH == "/opt" ] || [ $LOGS_PATH == "/usr" ];then
  echo "Nginx logs path is not right!!!" >> ${logfile}
  exit 1;
fi

if [ -z "$LOGS_PATH" ];then
  echo "Nginx logs path is null!!!" >> ${logfile}
  exit 1;
fi

if [ -z "$SAVE_DAYS" ];then
  SAVE_DAYS=7
fi
echo "Security check success." >> ${logfile}

echo "Move and rename logs start."
if [ -f ${LOGS_PATH}/error_${TODAY}.log.gz ];then
  TODAY=$CURRENTTIME
fi

if [ -f ${LOGS_PATH}/access_${TODAY}.log.gz ];then
  TODAY=$CURRENTTIME
fi

echo "Move and rename logs finished."

#bak log files
mv ${LOGS_PATH}/error.log ${LOGS_PATH}/error_${TODAY}.log
mv ${LOGS_PATH}/access.log ${LOGS_PATH}/access_${TODAY}.log

#RESTART nginx process open file pid
kill -USR1 `cat ${
      PID}`

#Compress xxx.log to xxx.log.gz and auto remove xxx.log
if [ -f "/usr/bin/gzip" ];then
  gzip ${LOGS_PATH}/error_${TODAY}.log
  gzip ${LOGS_PATH}/access_${TODAY}.log
fi
echo "Move and rename logs success." >> ${logfile}

echo "Command: find ${LOGS_PATH} -type f -mtime +{SAVE_DAYS} | xargs rm -f" >> ${logfile}
echo "clear files:" >> ${logfile}
find ${LOGS_PATH} -type f -mtime +${SAVE_DAYS} -print >> ${logfile}
find ${LOGS_PATH} -type f -mtime +${SAVE_DAYS} | xargs rm -f

echo "`date +%Y-%m-%d` `date +%H-%M-%S` End run the shell $0." >> ${logfile}
exit 0

你可能感兴趣的:(服务器,实用分享,nginx,服务器,运维)