Linux下添加shell腳本使得nginx日志每天定時切割壓縮


Linux下添加shell腳本使得nginx日志每天定時切割壓縮
一 簡介

對於nginx的日志文件,特別是access日志,如果我們不做任何處理的話,最后這個文件將會變得非常龐大


這時,無論是出現異常時查日志,還是使用“GoAccess”等工具對日志進行分析都將會變得非常麻煩。因此,每天定時對nginx日志進行切割壓縮就非常有必要了

二 實現

我的實現思路是每天晚上接近12點時定時執行腳本。其腳本內容就是將當前的nginx日志先按照當天日期進行重命名接着進行壓縮,最后是新建空白的nginx日志文件,並重新載入nginx

[root@localhost ~]# cd /usr/local
[root@localhost local]# mkdir scripts
[root@localhost 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
給腳本添加可執行權限:

[root@localhost scripts]# chmod a+x nginxLog.sh
添加定時任務(每天23:40執行):

[root@localhost scripts]# cd /var/spool/cron/
[root@localhost cron]# echo "40 23 * * * /usr/local/scripts/nginxLog.sh" > root
查看任務:

[root@localhost cron]# crontab -l
這樣,第二天就可以看到效果了。最后的效果如下圖所示:
wKiom1g7jvTQIhutAAAXVwvG1yI313.png
注:如果有多個nginx日志文件的話可以考慮將我上面的腳本改成更加通用的形式
附:nginx日志定時清理腳本:

[root@localhost 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 {}
注:上面腳本的意思是刪除當前天之前一個月那天的日志文件

給腳本添加可執行權限:

[root@localhost scripts]# chmod a+x /usr/local/scripts/cleanNginxLog.sh
添加一條定時任務(每天0:30執行):
[root@localhost scripts]# echo "30 0 * * * /usr/local/scripts/cleanNginxLog" >> /var/spool/cron/root

 

以上部分來自網絡博客,本人做了一些總結

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM