linux文件增长定时切割,Linux下添加shell脚本使得nginx日志每天定时切割压缩(示例代码)...

Linux下添加shell脚本使得nginx日志每天定时切割压缩

一 简介

对于nginx的日志文件,特别是access日志,如果我们不做任何处理的话,最后这个文件将会变得非常庞大

这时,无论是出现异常时查日志,还是使用“GoAccess”等工具对日志进行分析都将会变得非常麻烦。因此,每天定时对nginx日志进行切割压缩就非常有必要了

二 实现

我的实现思路是每天晚上接近12点时定时执行脚本。其脚本内容就是将当前的nginx日志先按照当天日期进行重命名接着进行压缩,最后是新建空白的nginx日志文件,并重新载入nginx

[[email protected] ~]# cd /usr/local

[[email protected] local]# mkdir scripts

[[email protected] scripts]# vim nginxLog.sh

其内容如下:

#!/bin/sh

cd /usr/local/nginx/logs/

newAccessLog="access`date +%Y-%m-%d`.log"

newErrorLog="error`date +%Y-%m-%d`.log"

mv access.log $newAccessLog

mv error.log $newErrorLog

#创建日志文件

touch access.log error.log

#reload Nginx

/etc/init.d/nginx reload

#压缩日志文件

tar -zcvf $newAccessLog.tar.gz $newAccessLog --remove-files

tar -zcvf $newErrorLog.tar.gz $newErrorLog --remove-files

给脚本添加可执行权限:

[[email protected] scripts]# chmod a+x nginxLog.sh

添加定时任务(每天23:40执行):

[[email protected] scripts]# cd /var/spool/cron/

[[email protected] cron]# echo "40 23 * * * /usr/local/scripts/nginxLog.sh" > root

查看任务:

[[email protected] cron]# crontab -l

这样,第二天就可以看到效果了。最后的效果如下图所示:

wKiom1g7jvTQIhutAAAXVwvG1yI313.png

注:如果有多个nginx日志文件的话可以考虑将我上面的脚本改成更加通用的形式

附:nginx日志定时清理脚本:

[[email protected] scripts]# vim /usr/local/scripts/cleanNginxLog.sh

其内容如下:

#!/bin/sh

cd /usr/local/nginx/logs/

find . -name "*`date -d ‘-1months‘ +%Y-%m-%d`*" -type f | xargs -I {} rm -f {}

注:上面脚本的意思是删除当前天之前一个月那天的日志文件

给脚本添加可执行权限:

[[email protected] scripts]# chmod a+x /usr/local/scripts/cleanNginxLog.sh

添加一条定时任务(每天0:30执行):

[[email protected] scripts]# echo "30 0 * * * /usr/local/scripts/cleanNginxLog" >> /var/spool/cron/root

以上部分来自网络博客,本人做了一些总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值