Shell脚本分割Nginx日志,并定期清理[不重启nginx]

AndyYang| 阅读:1322 发表时间:2016-05-03 19:23:22 linux
摘要:之前写过一篇关于 Shell脚本分割Nginx日志,并定期清理 的文章,但是需要reload nginx,有些人对重启nginx有心理阴影,所以又改了下~

之前写过一篇关于 Shell脚本分割Nginx日志,并定期清理 的文章,链接:http://www.webyang.net/Html/web/article_255.html 但是需要reload nginx,有些人对重启nginx有心理阴影,所以又改了下:

#!/bin/bash
#nginx access log segmentation shell script
#日志目录
log_dir="/usr/local/nginx/logs/"
cd $log_dir
time=`date +%Y%m%d --date="-1 day"`
#日志保存天数
save_days=15
#日志文件名所处'/'分割的位置,key('/'数+1)
num=6;

#此处待优化(取得文件不带后缀的文件名)
website=`ls $log_dir*.log | xargs -n 1 | cut -f 1 -d "." | cut -f $num -d "/"`
#日志目录下所有的日志文件为文件夹,循环新建对应的时间文件
for i in $website
do
    #判断目录是否存在
    if [ ! -d $log_dir$i ];then
        mkdir "$i"
    fi

    cp $log_dir$i.log $log_dir$i/$i-$time.log
    true>$log_dir$i.log
done

find $log_dir -mtime +$save_days -exec rm -rf {} \;

设置crontab,每天凌晨跑一次。
展示: web1.log => web1/web1-20160322.log web1/web1-20160323.log web2.log => web2/web2-20160322.log web2/web2-20160323.log

其他还有 cronolog、logrotate等方式,可以参考:http://www.tuicool.com/articles/BF36rq

本文为AndyYang原创,转载请注明出处!
如果您觉得好,可以打赏作者:
如果您觉得累了,是否想看点美女养养眼:猛戳>>朋友帮
如果您觉得皮了,是否想来点神吐槽:猛戳>>iPhone查询中

已有0条评论

昵称:
邮箱:

  • 最新评论

iPhone查询中 - bbs.ipcxz.com 朋友帮 - www.pengyb.cn iPhone查询中 - bbs.ipcxz.com
反馈
微信订阅号