LoginSignup
25
27

More than 5 years have passed since last update.

自前でログローテートする

Last updated at Posted at 2014-07-18

何らかの理由で手動でログローテートをするときのスクリプト

#!/bin/sh
#Log Rotation Script AM 0:00

# ログファイルが置かれているフォルダ
LOGDIR="/usr/local/nginx/logs"
# ログファイルを保管するフォルダ(今は同じフォルダに保管してる)
OLDLOGDIR="/usr/local/nginx/logs"

sleep 1

DATE=`date +%Y%m%d --date '1 day ago'`

for file in access.log
do
    sudo -u root /bin/cp ${LOGDIR}/${file} ${OLDLOGDIR}/${file}.$DATE

    if [ $? = 0 ];then
        sudo -u root /bin/cp /dev/null ${LOGDIR}/${file}
        # 必要なら個々でgzipなどする
    fi

    # delete log file before 6 days
    # 削除対象が存在しない時のために --no-run-if-empty オプションを指定
    /usr/bin/find ${OLDLOGDIR}/${file}.* -mtime +5 | xargs --no-run-if-empty /bin/rm

   echo "finish rotate ${file}"
done

複数のファイルが対象の時

対象ファイル名をリストで持って、forで回す

targets="access.log error.log"

for file in $targets
do
  # 上記と同じでOK
done
25
27
4

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
25
27