原创, 服务器,

自动清理Docker log脚本,清理java应用log脚本

清理Docker log脚本

/data/remove-docker-log.sh

#!/bin/bash

logs=/var/lib/docker/containers

for containerPath in `ls $logs`
do
 log=${logs}/${containerPath}/${containerPath}-json.log
 echo "" > $log
 actionDate=`date "+%Y-%m-%d %H:%M:%S"`
 echo "${actionDate} - clean docker file ${log} success"
done  # end application

每2小时清理一次

0 */2 * * * /data/remove-docker-log.sh >> /data/remove-docker-log.log 2>&1

清理Java 应用程序脚本

/data/remove-java-application-log.sh

#!/bin/bash
#前60天
startDate=`date -d "-60 days" "+%Y-%m-%d"`
echo ${startDate}

#前2天
endDate=`date -d "-2 days" "+%Y-%m-%d"`
#endDate=`date "+%Y-%m-%d"`
echo ${endDate}

logs=/data/logs

startDateTmp=`date -d ${startDate} +%s`
endDateTmp=`date -d ${endDate} +%s`

for application in `ls $logs`
do
 echo "start scan ${logs}/${application}"
 for log in `ls ${logs}/${application}`
 do
  tempStartDate=${startDate}
  tempStartDateTmp=`date -d ${tempStartDate} +%s`
  
  while (( tempStartDateTmp < endDateTmp ))
  do
   if [[ ${log} =~ ^[a-zA-Z0-9-]+.${tempStartDate}.[0-9]*.[log]+ ]]
   then 
    tempStartDateTmpBefore=$((${tempStartDateTmp}+5*24*3600))
    actionDate=`date "+%Y-%m-%d %H:%M:%S"`
    if [[ (${log} =~ "error" || ${log} =~ "warn") && $tempStartDateTmpBefore > $endDateTmp ]]
    then
     echo "${actionDate} - ignore file ${logs}/${application}/${log}"
    else
     echo "${actionDate} - del success ${logs}/${application}/${log}"
     find ${logs}/${application}/${log} -type f -name "*.log" | xargs rm -rf
    fi
   fi
   tempStartDate=`date -d "${tempStartDate} +1 days" "+%Y-%m-%d"`
   tempStartDateTmp=`date -d ${tempStartDate} +%s`
  done # end while
 done # end log
done  # end application

清理掉3天前的log, 每天2点清理

0 2 * * * /data/remove-java-application-log.sh >> /data/remove-java-application-log.log 2>&1

(292)

Related Post