nginx日志自动按日期切割保存七天内容
编写日志切割shell
#!/bin/sh
LOGS_PATH=/usr/local/webserver/nginx/logs
PID=/usr/local/webserver/nginx/logs/nginx.pid
SAVE_DAYS=7
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."
mv ${LOGS_PATH}/error.log ${LOGS_PATH}/error_${TODAY}.log
mv ${LOGS_PATH}/access.log ${LOGS_PATH}/access_${TODAY}.log
kill -USR1 `cat ${PID}`
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