Thursday, March 3, 2011

Monitor log file and send email alert when error occurs

I ran into a situation where I had an error occuring periodically, and I needed an easy way to be notified whenever the error occured, so that I could make some configuration changes to my server.  This script is fairly simple and should be able to be modified to fit many needs.  It basically looks at the tail of any given log file, and searches for a specific error code, or string.  Any time this error code occurs an email alert is sent out, and then the script sleeps for a given period (as to not flood my email box).


######################################################################
#!/bin/bash


errorString='SC-001'
recipient="xxsyntax@gmail.com"
sleepTime=10
logFile='/var/log/program/log'


x=1
while [ $x -gt 0 ] 
do
   checkLog=`tail $logFile | grep $errorString`
   if [[ $checkLog == *$errorString* ]]
      then
      echo "Error found, sending an email."
      echo "$checkLog" | mail -s "Alert:  $errorString" $recipient
      sleep $(( $sleepTime * 60 ))
   fi
done

######################################################################

No comments:

Post a Comment