Bash Script – An Alternative to Logrotate.d for Asterisk Log Files

For the longest time, I was having trouble getting the log rotate daemon to work properly with Asterisk. I tried using both postrotate and prerotate options on Ubuntu Server and no matter what, I always ended up with dozens or even hundreds of files if I wasn’t keeping a close eye on them. I never figured out why or wanted to spend a ton of time searching for answers but for some reason, the numbering on the log files would always get messed up and it would start adding extra periods on the end of the filenames and everything would get all out of whack.

Eventually, I got fed up with it and wrote this cheap ass script to run as a cron job every night at midnight and have never had a problem since. Also, I despise having to untar log files just to look at them and I had plenty of server space to spare so there aren’t any provisions to zip the files up but that should be easy enough for you to add if you want it.

Download it now – astlogrotate.sh

#!/bin/bash
#
# Asterisk Log File Rotation
# By Nathan Thomas
# 06-01-2014
# This will keep the current log file which is created 
# at the time the script is ran, plus files ending in 0-6
# In /etc/asterisk/logger.conf, set rotatestrategy=rotate

DAYSTOKEEP='7'
LOGDIR='/var/log/asterisk'
LOGFILES=('full' 'messages')
ROTATEFLAG='on'

for items in "${LOGFILES[@]}" ; do
   if [ -f "${LOGDIR}/${items}" ] ; then
      if [ "${ROTATEFLAG}" = "on" ] ; then
         /usr/sbin/asterisk -rx 'logger rotate' > /dev/null 2>&1
         ROTATEFLAG='off'
         rm -f "${LOGDIR}/${items}.${DAYSTOKEEP}"
      else
         rm -f "${LOGDIR}/${items}.${DAYSTOKEEP}"
      fi
   else
      /usr/sbin/asterisk -rx 'logger reload' > /dev/null 2>&1
      ROTATEFLAG='off'
   fi
done

Leave a Reply