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

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

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4992249.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存