简体   繁体   中英

How to scan a log file for errors in bash

I want to scan a log file for JDBC and JMS exception and send an e-mail if such error is found.

Issue here with tail are:

  1. I cannot execute shell script periodically
  2. If someone kills tail command invoked from my shell script then I will no longer receive e-mail alerts.

So far I have developed below script:

#!/bin/bash
#This shell script monitors application logs file and sends alert email in case of JDBC or JMS error.

export LOGFILE=/usr/app/$USER/data/logs/dummyapp.log
export EMAILRECIPIENTLIST="opsteamdl@company.com"

#-------------------------------------------------------------------------
#----------- DO NOT EDIT AFTER THIS LINE ---------------------------------
#-------------------------------------------------------------------------
echo "Scanning log file - $LOGFILE"
tail -f $LOGFILE|while read line;
do
echo $line
if [ `echo $line|grep JDBCConnectionException|wc -l` -ne 0 ]; then
        mailx -s "[URGENT] - JDBCConnectionException reported in log" $EMAILRECIPIENTLIST < echo $line;
else if [ `echo $line|grep javax.jms.JMSException|wc -l` -ne 0 ]; then
        mailx -s "[URGENT] - javax.jms.JMSException reported in log" $EMAILRECIPIENTLIST < echo $line;
fi
fi
done
exit

Your script looks fine, just few refinements:

tail -f $LOGFILE|while read line;
do
echo "$line"
if $(echo $line|grep -Eq "JDBCConnectionException")
then
    echo "$line" | mailx -s "[URGENT] - JDBCConnectionException reported in log" $EMAILRECIPIENTLIST && pkill -P $$ tail
elif $(echo $line|grep -Eq "javax.jms.JMSException")
 then
    echo "$line" | mailx -s "[URGENT] - javax.jms.JMSException reported in log" $EMAILRECIPIENTLIST && pkill -P $$ tail
fi
done

======================================================

pkill -P $$ tail : to kill the tail command started by your script. If you want your script to be running , you can exclude this part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM