Total Hit Counter

Monday, December 3, 2012

Script to monitor error in log file



Script to monitor error in log file


#!/bin/bash
#####
# The Script will check the pattern in mentioned file
# Author: Shankar Patel
################################################################################
function help {
echo "The plugin will check the pattern in mentioned file
Usage:
$0 -p <Pattern> -f <file>
Options:
p - Patern to be matched
f - file to monitor given pattern.
h - help.
examples:
$0 -p 'file' -f /var/log/messages
OK. 'file' not found in /var/log/messages | error_found=0"
exit 3;
}

while getopts "p:f:h" OPT; do
case $OPT in
"p") PATTERN=$OPTARG;;
"f") FILE2TAIL=$OPTARG;;
"h") help ;;
esac
done

if [ "$PATTERN" = "" ] || [ "$FILE2TAIL" = "" ] ; then help ; fi

FPATH=$(dirname $FILE2TAIL)
FFILE=$(basename $FILE2TAIL)
INODE_NUM=$(ls -i ${FPATH}/${FFILE} | awk '{ print $1 }')
PATTERN_CODE="$(echo -n "$PATTERN"|tr -d \* | tr -d ' ' | tr -d \. )"
FSIZE_FILE=${FPATH}/.${FFILE}_${PATTERN_CODE}_${INODE_NUM}.size
SIZE_CURRENT=$(ls -l ${FPATH}/${FFILE} | awk '{ print $5 }')
exit_status=0

last_exit()
{# save current size
ls -l ${FPATH}/${FFILE} | awk '{ print $5 }' > ${FSIZE_FILE}
/bin/rm -f /tmp/ts$$ /tmp/tsF$$
exit $exit_status
}
if [ ! -f ${FSIZE_FILE} ]; then
# first time, save line count
echo "OK. saving initial size of ${FPATH}/${FFILE} | error_found=0"
last_exit
fi

# last size is available
SIZE_LAST=$(cat ${FSIZE_FILE})
SIZE_DELTA=$(($SIZE_CURRENT - $SIZE_LAST))
if [ $SIZE_DELTA -gt 0 ]
then
# new bytes to scan
tail "-${SIZE_DELTA}c" ${FPATH}/${FFILE} > /tmp/ts$$
egrep "$PATTERN" /tmp/ts$$ > /tmp/tsF$$
GREP_STATUS=$?
if [ $GREP_STATUS -eq 0 ]
then
echo "CRITICAL. '$PATTERN' found in '${FFILE}' file | error_found=1"
exit_status=2
last_exit
else
# found no matches
echo "OK. '$PATTERN' not found in '${FFILE}' file | error_found=0"
exit_status=0
last_exit
fi

else
# found no matches
echo "OK. '$PATTERN' not found in '${FFILE}' file | error_found=0"
exit_status=0
last_exit
fi

No comments: