shell脚本限制日志文件大小和行数

背景: 项目server在后端持续运行,日志文件不断变大,需及时进行清空。

解决方案:编辑sh脚本,指定时间间隔轮询;将超出限制的日志文件,先备份,再清空原日志文件内容。

清空日志文件内容的方法有:

            1.  echo "" > test.log

            2. cat /dev/null > test.log

            3. cp /dev/null test.log

            4.  > test.log

            5. truncate -s 0 test.log

1.限制指定日志文件大小(1024*10字节)

#!/bin/sh

function limit_size_log(){  
    local logfile=$1  
    local maxsize=$2 

    if [ ! -f "$logfile" ]; then
    sudo touch $logfile
    fi

    filesize=`ls -l $logfile | awk '{ print $5 }'`

    if [ $filesize -gt $maxsize ]

    then

        echo "$filesize > $maxsize"

        sudo cp $logfile $logfile"`date +%Y-%m-%d_%H:%M:%S`".log

        sudo cp /dev/null $logfile

    else

        echo "$filesize < $maxsize"

    fi

}

# running
while true
do
    limit_size_log /var/log/test.log (1024*10)
    sleep 60
done

2. shell 脚本限制指定日志文件行数(10000行)

#!/bin/sh

function limit_count_log(){  
    local logfile=$1  
    local maxline=$2 

    if [ ! -f "$logfile" ]; then
    sudo touch $logfile
    fi
    linecount=`/usr/bin/wc -l $logfile|awk '{print $1}'`;  
    if [ ${linecount} -gt ${maxline} ];then    
        #delcount=`expr ${linecount} - ${maxline}`;       
        #sudo sed -i "1,${delcount}d" $logfile    
        sudo cp $logfile $logfile"`date +%Y-%m-%d_%H:%M:%S`".log
        sudo tar -czPvf $logfile"`date +%Y-%m-%d_%H:%M:%S`".log.tar.gz $logfile"`date +%Y-%m-%d_%H:%M:%S`".log
        sudo rm $logfile"`date +%Y-%m-%d_%H:%M:%S`".log
        sudo cp /dev/null $logfile
    else    
        echo  $linecount
    fi
}

# running
while true
do
    limit_count_log /var/log/test.log 10000
    sleep 60
done

猜你喜欢

转载自blog.csdn.net/LeonTom/article/details/82945422
今日推荐