编写背景:
多个后台应用的日志分别在各个应用下面的logs下面info.log、debug.log、error.log,没隔一天会将这三个日志加上日期(但文件名最后有一个空格),先需要将所有有日期的日志放到同一目录,当天的日志每隔一小时同步一次。
定时任务设定
vi /etc/corntab
1 0 * * * * root /opt/log/getLog.sh
2 0 1 * * * root /opt/log/bakLog.sh
定时将日志输出到指定目录,并打包(单个文件打包)【bakLog.sh】
1 #!/bin/bash
2
3 backupLog()
4 {
5 FROMDIR=$1;
6 TODIR=$2;
7
8 if [[ -z "$FROMDIR" || -z "$TODIR" ]]; then
9 echo "parameter error!";
10 return;
11 fi
12
13 if [ ! -d $TODIR ]; then
14 mkdir -p $TODIR
15 fi
16
17 cd $FROMDIR
18 find . -name "*.log.*" | awk -F " " '{sub("./","");print $1}' | xargs -i cp "{} " $TODIR/{}
19 cd $TODIR
20 find . -name "*.log.????-??-??" -exec tar -zcf "{}.tar.gz" {} ;
21 find . -name "*.log.????-??-??" | awk -F / '{sub("./","");print}' | xargs rm -rf ;
22 }
23
24 GUANGSOFT=/opt/GuangheHome
25 LOGDIR=/opt/log
26
27 backupLog $GUANGSOFT/guanghe/logs $LOGDIR/guanghe
定时将日志输出到指定目录,并打包(同一日期日志放到同一文件夹,再将文件夹打包)【bakLog.sh】
1 #!/bin/bash
2
3 backupLog()
4 {
5 FROMDIR=$1;
6 TODIR=$2;
7 DATESTR=$(date -d '1 days ago' +%Y%m%d)
8 DATEDIR=$(date -d '1 days ago' +%Y-%m-%d)
9
10 if [[ -z "$FROMDIR" || -z "$TODIR" ]]; then
11 echo "parameter error!";
12 return;
13 fi
14
15 if [ ! -d $TODIR/$DATESTR ]; then
16 mkdir -p $TODIR/$DATESTR
17 fi
18
19 cd $FROMDIR
20 find . -name "*.log."$DATEDIR" " | awk '{sub("./","");print}' | xargs -i cp {} $TODIR/$DATESTR/{}
21 cd $TODIR
22 if [ "$(ls -A)" != "" ]; then
23 tar -zcf ${DATESTR}.tar.gz $DATESTR
24 fi
25 rm -rf $DATESTR
26 }
27
28 GUANGSOFT=/opt/ECSNHome
29 LOGDIR=/opt/log
30
31 backupLog $GUANGSOFT/guanghe/logs $LOGDIR/guanghe
定时同步日志到指定目录【getLog.sh】
1 #!/bin/bash
2
3 transferLog()
4 {
5 FROMDIR=$1;
6 TODIR=$2;
7 FILES=$3;
8
9 if [[ -z "$FROMDIR" || -z "$TODIR" || ${#FILES[@]} -le 0 ]]; then
10 echo "parameter error!";
11 return;
12 fi
13
14 if [ ! -d $TODIR ]; then
15 mkdir -p $TODIR
16 fi
17
18 for VAR in ${FILES[*]}
19 do
20 cp -r $FROMDIR/$VAR $TODIR/$VAR
21 done
22
23 }
24
25 GUANGSOFT=/opt/GuangheHome
26 LOGDIR=/opt/log
27 FILES=(info.log debug.log error.log)
28
29 transferLog $GUANGSOFT/guanghe/logs $LOGDIR/guanghe $FILES
30
31
32