linux系统中定时清理日志实现方法

需求

项目中使用maxwell监听mysql的binlong后,将消息日志打印到log文件.需要类似log4j的形式,记录最近n天的日志

脚本

#!/bin/bash
target_dir="/home/apprun/maxwell/script"
prefix_log="maxwell-"
prefix_sh="start-maxwell_"
postfix=".out"
ipArr=("172.16.32.227" "172.20.3.64" "172.20.3.65" "172.20.3.71");
keep_days=2
start_days=$(($keep_days - 1))
today=`date +%Y_%m_%d`
yesterday=`date -d yesterday +%Y_%m_%d`
delday=`date -d -2day +%Y_%m_%d`
dateArr[0]=`date +%Y_%m_%d`
hitory_days_count=$[$keep_days+1]
for ((i=1;i<=$history_days_count;i++))
do
dateArr[$i]=`date -d -$i'day' +%Y_%m_%d`
echo ${dateArr[$i]}
done
for i in ${ipArr[*]};do
echo $i
PID=`ps -ef | grep maxwell | grep "$i" | awk '{print $2}'`
echo "pid="$PID
#杀死进程
echo "---------------"
for id in $PID
do
kill -9 $id
echo "killed $id"
done
echo "---------------"
#文件迁移
file_name=$prefix_log$i
echo $i;
for n in $(seq $keep_days -1 1)
do
before=$[$n+1]
if [ -f $target_dir/$file_name"_"${dateArr[$n]}$postfix ]; then mv $target_dir/$file_name"_"$n$postfix $target_dir/$file_name"_"${dateArr[$before]}$postfix; fi
done
if [ -f $target_dir/$file_name$postfix ]; then mv $target_dir/$file_name$postfix $target_dir/$file_name"_"${dateArr[1]}$postfix; fi
touch $target_dir/$file_name$postfix;
#maxwell重启
tmpsh=$target_dir"/"$prefix_sh$i".sh"
sh $tmpsh
echo "maxwell "$i" sh done"
do

相关推荐