用shell+crontab定时清理日志

背景简介

每小时扫描指定日志目录,文件超过100M后直接清空处理,作为运维的一个临时手段使用。

源码主要由两个函数构成:

  1. reviewLogs() 判断日志大小,并做清空处理;
  2. getdir() 判断是目录还是文件,如果是目录则进行迭代查找;

使用方法:

  1. 在~/folder_sj目录(自行重命名,shell源码中也要做同名替换)下新建review_logs.sh并贴入源码
  2. shell源码倒数第3行,配置需要扫描的路径,目录中所有的文件都会被扫描和处理,请注意不止是*.log
  3. reviewLogs()函数中 if [ $filesizeM -gt 100 ] 中的100是文件大小,单位是M,数值根据需要修改即可
  4. 配置完成后查看日志是否定时输出,日志所在路径是
    LOG=~/folder_sj/review_logs_${TIMESTAMP}.log

Shell源码

#!/bin/bash

TIMESTAMP=`date +%Y%m`
LOG=~/folder_sj/review_logs_${TIMESTAMP}.log
echo "Start to review all log files  at `date`." >>${LOG}


function reviewLogs(){
    filename=$1
    filesize=`ls -l $filename | awk '{ print $5 }'`
    filesizeM=`echo "sclae=2; $filesize/1024/1024" | bc`
    if [ $filesizeM -gt 100 ]
    then
      echo "$filename is too bigger!!"  >>${LOG}
      echo '' > $filename
      filesize1=`ls -l $filename | awk '{ print $5 }'`
      filesizeM1=`echo "sclae=2; $filesize1/1024/1024" | bc`
      echo "now the file size is ${filesizeM1} !!"  >>${LOG}
      echo "==========================="  >>${LOG}
    fi
}

function getdir(){
    for element in `ls $1`
    do
        dir_or_file=$1"/"$element
        if [ -d $dir_or_file ]
        then
            getdir $dir_or_file
        else
            reviewLogs $dir_or_file
        fi
    done
}

getdir '/opt/apache-tomcat-7.0.70_app/logs'

echo "Stop to review all log files  at `date`." >>${LOG}
echo "============================================================================" >>${LOG}

Crontab配置源码

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
00 */1 * * * root /root/folder_sj/review_logs.sh

猜你喜欢

转载自blog.csdn.net/yu36yuqing/article/details/81269990
今日推荐