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

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

编写日志切割shell

#!/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

定时器执行切割文件

查看crond的启动状态:
    service crond status 
 启动crond服务:
    service crond start 
 打开配置文件命令:
    /usr/bin/crontab -e
 定时任务脚本书写格式:
    */1 * * * * /bin/sh /usr/nginx/nginx/tools/clearNginxLog.sh
 实时查看cron执行日志:
    tail -f /var/log/cron
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值