linux logrotate 删除某天前

crontab

crontab -l
01 */2 * * * /usr/sbin/logrotate -v /opt/shell_app/appengine >/tmp/logrotate.log 2>&1

logrotate

$ cat /opt/shell_app/appengine 
compress
daily
size 10M
missingok
rotate 7

/ebs_data/opt/typhoonae/var/log/http*.log
{
    rotate 1
    prerotate
        /opt/shell_app/cut.sh ${1}.2.gz
    endscript
    postrotate
        kill -USR1 $(/sbin/pidof nginx) > /dev/null 2>&1 || true
    endscript
    create 644 steve steve
}

/opt/proftpd/var/*.log
/opt/gltfs/*.log
/opt/redis/var/*.log
{
    copytruncate
    prerotate
        /opt/shell_app/cut.sh ${1}.8.gz
    endscript
}

shell cut.sh

#!/bin/sh
#usage:add this script to logrotate's prerotate/endscript
#${1} is the absolute path to the log file
#${1}.3.gz means which file to bak and 3 is rotate's count add 1
#e.g.
#prerotate
#       /opt/shell_app/cut.sh ${1}.3.gz
#endscript

set -x
if [ -f $1 ]; then
        filepath=${1}
        filedir=$(dirname ${1})
        filename=$(basename ${1})
else
        exit 0
fi

c_date=$(date +%Y%m%d%H%M%S)
y_date=`date --date="1 days ago" +%Y%m%d`
w_date=`date --date="3 days ago" +%Y%m%d`

function clean_and_bak_log(){
    if [[ -d ${filedir}/bak ]];then
        echo "bak dir is exsited"
    else
        mkdir -p ${filedir}/bak
        chmod a+w ${filedir}/bak
    fi
    #insert current time to filename
    #${#filename}-3} means cut '.gz' from filename
    #example cp /opt/shell_app/test.log.3.gz /opt/shell_app/bak/test.log.3.201703061814.gz
    cp -p ${filedir}/${filename} ${filedir}/bak/${filename:0:${#filename}-3}.${c_date}.gz
    #rm -f ${filedir}/bak/*${w_date}*.gz
    find ${filedir}/bak/ -regextype posix-extended -regex '^.*[0-9]{14,14}\.gz$' -mtime +5 -print0 | xargs -0 /bin/rm -f

}

备注:若某天日志量较大,使用以上策略可能会对磁盘空间产生压力

参考链接:
gnu findutils

转载于:https://blog.51cto.com/chaoyuezhangsan/2065003

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值