ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

Nginx日志清理脚本

2021-01-22 10:31:51  阅读:236  来源: 互联网

标签:log nginx clear 清理 access Nginx error date 日志


Nginx日志清理脚本


适用环境

使用Bash为默认shel且符合LSB标准的Linux系统。

脚本功能

  • 配合crontab任务,此脚本可实现定期清理nginx日志的功能。

  • 例如:当设定定时清理时间为30天,且配置crontab任务为如下时。此脚本可实现每天1:00清理30天前的nginx日志。

    0 1 * * * /home/suifenpx/nginx_log_clear.sh
    

使用方法

  • 修改nginx_access_log变量的值为Nginx的access日志的路径。
  • 修改nginx_error_log变量的值为Nginx的error日志的路径。
  • 修改clear_date变量的值为清理日志的时间限制(例如:当值为30时,表示清理30天前的日志)。

脚本

#!/bin/bash

:<<!
    功能:Ningx日志清理
    版本:0.4a
    注意:使用前需修改如下变量的值:
        1、修改nginx_access_log变量的值为Nginx的access日志的路径。
        2、修改nginx_error_log变量的值为Nginx的error日志的路径。
        3、修改clear_date变量的值为清理日志的时间限制(例如:当值为30时,表示清理30天前的日志)。
    作者:SuiFenPX
    邮件:suifenpx@qq.com
    日期:2020-12-29
!

nginx_access_log=/home/suifenpx/access.log
nginx_error_log=/home/suifenpx/error.log
clear_date=30

last_month_4a=`date -d "-\$clear_date days" +%d\\\/%b\\\/%Y`
last_month_4e=`date -d "-\$clear_date days" +%Y\\\/%m\\\/%d`
tmp_file_4a=$nginx_access_log.tmp
tmp_file_4e=$nginx_error_log.tmp
now_date=`date +"%Y-%m-%d %H:%M:%S"`

function clear_access_log() {
    sed -n "/$last_month_4a/,\$p" $nginx_access_log > $tmp_file_4a
    cat $tmp_file_4a > $nginx_access_log
    rm -rf $tmp_file_4a
    echo -e "$now_date [SUCCESS] $clear_date天前的Nginx access日志已清理!"
}

function clear_error_log() {
    sed -n "/$last_month_4e/,\$p" $nginx_error_log > $tmp_file_4e
    cat $tmp_file_4e > $nginx_error_log
    rm -rf $tmp_file_4e
    echo -e "$now_date [SUCCESS] $clear_date天前的Nginx error日志已清理!"
}

if [ -e $nginx_access_log ] && [ -e $nginx_error_log ];then
    clear_access_log
    clear_error_log
    exit
elif [ -e $nginx_access_log ] && [ ! -e $nginx_error_log ];then
    clear_access_log
    echo -e "$now_date [ERROR] 未找到$nginx_error_log文件!"
    exit
elif [ ! -e $nginx_access_log ] && [ -e $nginx_error_log ];then
    clear_error_log
    echo -e "$now_date [ERROR] 未找到$nginx_access_log文件!"
    exit
elif [ ! -e $nginx_access_log ] && [ ! -e $nginx_error_log ];then
    echo -e "$now_date [ERROR] 未找到$nginx_access_log文件!"
    echo -e "$now_date [ERROR] 未找到$nginx_error_log文件!"
    exit
fi

标签:log,nginx,clear,清理,access,Nginx,error,date,日志
来源: https://blog.csdn.net/SuiFen_PX/article/details/112978638

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有