Tuesday, May 7, 2013

logging in bash - nice subroutine to reuse

I had a need to support good logging capabilities in bash. The reason was that there were quite a few scripts which needed consistent logs being rolled over every day. Here is the solution which I have come up with. As a result, a separate log file is created with datestamp in the filename.



# Function to write to the Log file
###################################

write_log() 
{
  while read text
  do 
      LOGTIME=`date "+%Y-%m-%d %H:%M:%S"`
      # If log file is not defined, just echo the output
      if [ "$LOG_FILE" == "" ]; then 
    echo $LOGTIME": $text";
      else
        LOG=$LOG_FILE.`date +%Y%m%d`
    touch $LOG
        if [ ! -f $LOG ]; then echo "ERROR!! Cannot create log file $LOG. Exiting."; exit 1; fi
    echo $LOGTIME": $text" | tee -a $LOG;
      fi
  done
}


It is easy to log any output to such subroutine, just pipe the output as folowing:
echo "Skipping to next copy" | write_log


If you want to also store the same output to another file, you can add another pipe:
echo " ^^^ ERROR while rsync $OUTPUTDIR." | write_log | tee -a $TEMP_DETAIL_FILE

1 comment:

  1. Thanks for saving my day by sharing this function...

    just a minor correction to initialize the $LOG_FILE variable

    ReplyDelete