ログを毎日ローテーションさせ、古いログを前日の日付入りで保存していくためのシェルスクリププトです。
▼access_log_rotation.sh
#!/bin/sh
#
# Apache access log rotation
#
LOGDIR=/var/log/httpd/ # log directory
LOGDIROLD=/home/svrmgr/log/httpd/ # old log directory
LOG=access_log # log file format
LOGOLD=access_log_ # old log file format
LOGEX=.log # log file extension
CALCPROG=/home/svrmgr/util/calc_date.pl # the program to calculate past date
if [ ! -r $LOGDIR -o ! -r $LOGDIROLD ]
then
echo “Log directory does not exist”
exit
fi
if [ ! -f $CALCPROG ]
then
echo “Date calculate program does not exist”
exit
fi
YESTERDAY=
cd $LOGDIR
if [ ! -f $LOGDIROLD$LOGOLD$YESTERDAY$LOGEX ]
then
cp $LOG $LOGDIROLD$LOGOLD$YESTERDAY$LOGEX # rename log
chown svrmgr:svrmgr $LOGDIROLD$LOGOLD$YESTERDAY$LOGEX # change user
cp /dev/null $LOG # init log
chmod 644 $LOG # change mode
fi
kill -HUP
exit
#
# Apache access log rotation
#
LOGDIR=/var/log/httpd/ # log directory
LOGDIROLD=/home/svrmgr/log/httpd/ # old log directory
LOG=access_log # log file format
LOGOLD=access_log_ # old log file format
LOGEX=.log # log file extension
CALCPROG=/home/svrmgr/util/calc_date.pl # the program to calculate past date
if [ ! -r $LOGDIR -o ! -r $LOGDIROLD ]
then
echo “Log directory does not exist”
exit
fi
if [ ! -f $CALCPROG ]
then
echo “Date calculate program does not exist”
exit
fi
YESTERDAY=
$CALCPROG -1
# get the date of yesterdaycd $LOGDIR
if [ ! -f $LOGDIROLD$LOGOLD$YESTERDAY$LOGEX ]
then
cp $LOG $LOGDIROLD$LOGOLD$YESTERDAY$LOGEX # rename log
chown svrmgr:svrmgr $LOGDIROLD$LOGOLD$YESTERDAY$LOGEX # change user
cp /dev/null $LOG # init log
chmod 644 $LOG # change mode
fi
kill -HUP
cat /var/run/httpd.pid
exit
cronに登録します。
# crontab -e
(以下、編集内容)
# rotate apache log
1 0 * * * /home/svrmgr/scripts/access_log_rotation.sh > /dev/null 2>&1
(以下、編集内容)
# rotate apache log
1 0 * * * /home/svrmgr/scripts/access_log_rotation.sh > /dev/null 2>&1
以下のように過去ログが保存されます。
# ls -l /home/svrmgr/log/httpd/
-rw-r–r– 1 svrmgr svrmgr 1557760 12月 2 00:01 access_log_20051201.log
-rw-r–r– 1 svrmgr svrmgr 1873220 12月 3 00:01 access_log_20051202.log
-rw-r–r– 1 svrmgr svrmgr 2024303 12月 4 00:01 access_log_20051203.log
-rw-r–r– 1 svrmgr svrmgr 2046945 12月 5 00:01 access_log_20051204.log
-rw-r–r– 1 svrmgr svrmgr 2003267 12月 6 00:01 access_log_20051205.log
…
-rw-r–r– 1 svrmgr svrmgr 1557760 12月 2 00:01 access_log_20051201.log
-rw-r–r– 1 svrmgr svrmgr 1873220 12月 3 00:01 access_log_20051202.log
-rw-r–r– 1 svrmgr svrmgr 2024303 12月 4 00:01 access_log_20051203.log
-rw-r–r– 1 svrmgr svrmgr 2046945 12月 5 00:01 access_log_20051204.log
-rw-r–r– 1 svrmgr svrmgr 2003267 12月 6 00:01 access_log_20051205.log
…