LoginSignup
18
19

More than 5 years have passed since last update.

シェルスクリプトでログローテート

Posted at

logrotate を使って下さい

yumでインストールして使って下さい。お願いします。
存在を知らなかったので作っちゃいました。
機能的にはだいたい同じです。

  • 再帰的にディレクトリを潜って処理する
  • 引数で開始ディレクトリを指定可能
  • 引数なしはカレントディレクトリ
  • 7日以前の圧縮ファイルは削除

キック用(cron)

cron_logrotate
58 23 * * * ekaneko /bin/bash /var/log/hoge_logs/logrotate.sh

スクリプト

logrotate.sh
#!/bin/bash
#
# ログローテート
#
cd `dirname $0`
# DIR_BASE='/var/log/hoge_logs'
DIR_BASE=`pwd`
# 翌日に実行する場合
# SUFFIX_DATE=`date +%Y%m%d --date '1 day ago'`
# 当日に実行する場合
SUFFIX_DATE=`date +%Y%m%d`
MYSELF_SH=$0

# 引数検査
if [ $# -ge 1 ];
then
    DIR_BASE=$1
    if [ ! -d $DIR_BASE ];
    then
        echo "if require arg1, use only directory."
        exit 1
    fi
fi

# ファイルリスト配列作成
unset ArrayFiles;
unset ArrayDirs;
for LINE in `ls -1 ${DIR_BASE} 2> /dev/null`;
do
    if [ -d $DIR_BASE/$LINE ];
    then
        # ディレクトリの場合
        ArrayDirs+=($LINE)
    else
        # if expr "aaa.log" : ".*\.log$" > /dev/null ; then echo "hit"; fi
        if expr $LINE : ".*\.log$" > /dev/null ;
        then
            # ファイルの場合
            ArrayFiles+=($LINE)
        fi
    fi
done
unset LINE;

for el in ${ArrayFiles[@]};
do
    # ログファイルサイズ0の場合は削除する
    if [ ! -s $el ];
    then
        rm $el >& /dev/null
        continue
    fi

    # ローテーション
    cp ${el} ${el}.${SUFFIX_DATE}
    cp /dev/null ${el}
    gzip -9 ${el}.${SUFFIX_DATE}

    # 圧縮ディレクトリに移動
    DestinationstDir=$DIR_BASE/arc
    if [ ! -d $DestinationstDir ];
    then
        mkdir -p $DestinationstDir
    fi
    mv ${el}.${SUFFIX_DATE}.gz $DestinationstDir
done

# 圧縮ディレクトリの古いファイルを削除
# + 7日以前の圧縮ファイルを削除
pushd $DIR_BASE/arc >& /dev/null
for l in `find ./*.gz -mtime +7`;
do
    if [ -f $l ];
    then
        rm -f $l >& /dev/null
    fi
done
popd >& /dev/null

# サブディレクトリがある場合は再帰的に処理を行う
for el in ${ArrayDirs[@]}; do
    eval "sh $MYSELF_SH $DIR_BASE/$el"
done

exit 0

困ったこと

ある日ログディレクトリを見ると、このスクリプトファイルが消えていました。
不思議に思いながら再度設置。
翌日確認するとまた消えていました。
xx日以前のファイル削除で拡張子を指定してませんでした。
なんとなく可愛いなコイツって思いました。

18
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
19