Continiously monitor the log file

Hi Friends,

I am trying to write a script which continiously monitor one specific error message from a log file. This script should continiously monitor the file for the error and send out the email when detect the error message. I tried the below command but fails. Please help me.

tail -f /var/log/messages | grep "file not found" | mail -s "error found" arumon@testing.com

Regards,
Arumon

run the command

tail -f /var/log/messages >>monitor.log &

put below monitor.sh in cronjob

$ cat monitor.sh

#!/bin/bash
n1=`awk '/file not found/{n++}END{print n}' monitor.log`
[ $n1 -ge 1 ] && mailx  -s "error found" arumon@testing.com
>my.log
*/5 * * * * monitor.sh

Thanks rcdwayx :slight_smile:

Have some doubts on this.

  1. As this new monitor.log file will have all time entries and the cron job will execute every 5 sec, I think this will send the old error messages again and again.
  2. Also i need to avoid the same erros to be send frequently if it is happening continiously.

Please help me.

Regards,
Arumon

check for every 5 second on evet about klogd

#./justdoit 5 klogd &

check for every 15 second on evet about klogd

#./justdoit 15 crond &
#!/bin/bash
## justdoit ##
while :; do
lstlf="$(grep "$2" /var/log/messages|sed -n '$p')"
sleep $1;lstll="$(grep "$2" /var/log/messages|sed -n '$p')"
if [[ "$lstlf" != "$lstll" ]] ; then
echo "There is a event about on '$2'"|mail -s "Changes detected!!.." arumon@testing.com ; fi;done

regards
ygemici

  1. the command " >my.log " will clean the log file each time. So you should not get old error messages.

  2. [ $n1 -ge 1 ] can be used to adjust with your request, and the cronjob frequency can be adjusted , for example, every 10 minutes.

[ $n1 -ge 5 ]

0,10,20,30,40,50 * * * * monitor.sh

with above changes, you will check the log every 10 minutes, and if found more than 5 errors, send mail to you. Otherwise, keep quiet.