Jul 302011
 
Shell Scripting

Below bash script can be used to do log file rotate in any application and archive zipped rotated log files for certain period of time. Here you can mention multiple log file names which you want to get rotated. A simple cronjob will do the trick to check and rotate the logs from time to time.

Be careful about active logs, as if it rotates a ACTIVE log the application may not be able to write further log entries to the log file.

log_rotate.sh

#!/bin/bash
if [ $# -eq 1 ] || [ $# -eq 2 ]; then
CONFIG_FILE=$1
LOGFILEARCHIVE_DIR=$2
DATE=`date +%F"-"%H%M`

ZIP() {
FILE_PATH=$1
if [ ! -z $LOGFILEARCHIVE_DIR ]; then
LOG_FILE=`echo $FILE_PATH | awk -F"/" '{print $NF}'`
cp -p $FILE_PATH $LOGFILEARCHIVE_DIR/$LOG_FILE"_"$DATE
rm -f $FILE_PATH
gzip $LOGFILEARCHIVE_DIR/$LOG_FILE"_"$DATE
else
cp -p $FILE_PATH $FILE_PATH"_"$DATE
rm -f $FILE_PATH
gzip $FILE_PATH"_"$DATE
fi
}

REMOVE() {
find $1 -type f -mtime +30 -exec rm {} \;
}

for path in `cat $CONFIG_FILE |grep -v "^#"`
do
if [ -f $path ]; then
/usr/sbin/lsof $path
ACTIVE=$?
if [ $ACTIVE != 0 ]; then
ZIP $path
fi
elif [ -d $path ]; then
for file in `ls -l $path |grep "^-" | awk '{print $NF}' | grep -v -E '*.gz|*.Z'`
do
/usr/sbin/lsof $path/$file >/dev/null 2>&1
ACTIVE=$?
if [ $ACTIVE != 0 ]; then
ZIP $path/$file
fi
REMOVE $path
done
fi
done
else
echo "Usage $0 {Conf File Path} {Move Directory(Optional)}"
fi

Create a logrotate.conf like below where it points to perticular log files and directories.
Use the file name while starting the script. See the syntax example to know hoe to use it.

logrotate.conf:

#/opt/Serverin1/ccapps/myjsp/logs (# mark excludes the dir from log rotation)

/opt/Serverin2/ccapps/myjsp/logs

/opt/Serverin3/ccapps/myjsp/logs/error.log

/opt/Serverin4/ccapps/myjsp/logs/admin.log

Usage:

./log_rotate.sh <Config File Path> <Move Directory>

./log_rotate.sh ./logrotate.conf /opt/logs/old/archive

Note: <Move Directory> is optional if you dont want a separate directory for keeping old archived logs then use like below.
It will keep all logs archived, rotated in the same directory mentioned in logrotate.conf file.

./log_rotate.sh <Config File Path>

./log_rotate.sh ./logrotate.conf


If you dont want that complexity then you can use logrotate tool to do the same easily. Please check this article for more info on the same.

  3 Responses to “Bash Script To Do Log File Rotate”

  1. Hi,

    thanks for the scipt, but, how can i remove older files in “move directory”?

    I’ve tried to add this line under the same yours, but don’t work..:

    find $2 -type f -mtime +7 -exec rm {} \;

    Can you help me?

Leave a Reply