Apache: How do you set up log rotation and archiving for Apache logs?
If you have a website and never have archived your apache logs, you may be surprised one day by running out of space due to logs using up all the free space on specific partition. Most people don’t think about archiving until it is too late. Here we set up a simple log rotation script which will work for apache 1.x and also for apache 2.x version as well. I have included comments in the script itself to help you understand what is going on throughout.
#!/bin/sh
#
# Created by: Sunny Walia
# Date created: 5/24/03
# Date Modified: 5/29/07
# Purpose: do any type of preprocessing before log.php can do its work.
# Also does log rotation and backup.
#
# Modification history:
# 5/25/03: added comments.
# Gzip and move to backup logs folder
# added config info on top
#
#
# configuration info
SERVERNAME="svr1"
WORKINGDIR="/admin/backups/$SERVERNAME/logs/"
BACKUPLOGSDIR="/admin/backups/$SERVERNAME/logs/archived/"
BACKUP_DIR="/admin/backups/$SERVERNAME/"
LOGDIR="/usr/local/apache2/logs/"
DATE=`date +%m%d%y%H`
APACHCTL_LOC="/usr/local/apache2/bin/"
#
mkdir $WORKINGDIR -p
mkdir $BACKUPLOGSDIR -p
mkdir $BACKUP_DIR -p
#
# move the logs into their temp name so apache can continue to write to it
mv ${LOGDIR}access_log ${LOGDIR}${SERVERNAME}_access_log.old
mv ${LOGDIR}error_log ${LOGDIR}${SERVERNAME}_error_log.old
#
# restart apache gracefully so it will finish what its doing and start a new log file
# when done serving current requests
${APACHCTL_LOC}apachectl graceful
#
# give some time to apache to finish serving pending requests (in secs)
sleep 15
#
# copy the files to our directory for processing
cp ${LOGDIR}${SERVERNAME}_access_log.old ${WORKINGDIR}${SERVERNAME}_access_log
cp ${LOGDIR}${SERVERNAME}_error_log.old ${WORKINGDIR}${SERVERNAME}_error_log
#
mv ${LOGDIR}${SERVERNAME}_access_log.old ${LOGDIR}${SERVERNAME}_access_log.$DATE
mv ${LOGDIR}${SERVERNAME}_error_log.old ${LOGDIR}${SERVERNAME}_error_log.$DATE
gzip ${LOGDIR}${SERVERNAME}_access_log.$DATE
gzip ${LOGDIR}${SERVERNAME}_error_log.$DATE
#
# we move instead of copy than delete since if mv fails, we still have originals
# mv can fail if target location is full
mv ${LOGDIR}${SERVERNAME}_access_log.$DATE.gz $BACKUPLOGSDIR
mv ${LOGDIR}${SERVERNAME}_error_log.$DATE.gz $BACKUPLOGSDIR
Let us make the script executable:
chmod +x script_name.sh
You can automate this to happen every day by putting it in your crontab:
crontab -e
1 0 * * * /path/to/this/script
This will rotate your logs at 12:01 AM every day.
————————————-
DISCLAIMER: Please be smart and use code found on internet carefully. Make backups often. And yeah.. last but not least.. I am not responsible for any damage caused by this posting. Use at your own risk.


