Thursday, 21 February 2013

Compress tomcat logs from cron rather than logrotate

The problem with Tomcat is that it is OS agnostic: those who do not understand unix are doomed to reinvent it.

Specifically Tomcat has its own substandard version of logrotate, which creates a new log file every day. Some times the archive is dated sometimes the live log is dated.

#! /bin/sh
#
# TPP 2013-02-21
#
# Tomcat apps use a variety of loggers, mostly log4j. 
# These rotate, conflicting with logrotate the unix log rotation system.
#
# Some files eg catalina.out 
# are rotated to a backup containing a date eg catalina.2013-01-06.log
# which can then be compressed with bz2 to catalina.2013-01-06.log.bz2
#

cd /var/log/tomcat6

# 2013-02-21
date=`date --rfc-3339=date`
year=`date +%Y`
timestamp=`date`

echo "${timestamp} Running ${0}"

for f in $(find catalina* |grep -v bz2 |grep -v '$date' |grep $year)
do 
 echo "bzip2 $f"
 bzip2 $f
done

# However others are active whilst containing a date 
# so we will find all and not compress the most recent

for l in 'localhost*' 'opt-db*' 'opt*' 'host-manager*' 'manager*'
do 
 previous="not_this_one"
 for f in $(find $l |grep -v bz2 |grep $year|sort)
 do
  if [ "${previous}" != "not_this_one" ]
  then
    echo "bzip2 ${previous}"
    bzip2 $previous
  fi
  previous=$f
 done
done


exit 0

Added /etc/cron.d/compress_crontab_logs

23 3 * * * root /etc/cron.daily/compress_tomcat_logs.sh

Tested on a fairly ancient SuSE and debian.

No comments:

Post a Comment