Skip to content

Instantly share code, notes, and snippets.

@skyler
Last active August 29, 2015 13:58
Show Gist options
  • Save skyler/9997931 to your computer and use it in GitHub Desktop.
Save skyler/9997931 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Send an email when a pattern is matched in a log file.
# Example usage:
# /usr/local/bin/logmonitor.sh /var/log/nginx/error.log '[crit|error]' skyler@coefficientinc.com
PROGNAME=$0
function usage {
echo "usage: $PROGNAME logfile pattern recipients lines"
echo "-logfile the log file to monitor"
echo "-pattern the grep pattern to match"
echo "-recipients comma-separated email addreses"
echo "-lines the number of surrounding lines to include. The default is 100."
}
# Show usage if we're missing the first three arguments
# or if the 4th is < 4 chars, which indicates that it probably isn't a valid list of recipients.
if [ $# -lt 3 ] || [ ${#3} -lt 4 ]; then
usage
exit 0
fi
LOGFILE=$1
PATTERN=$2
RECIPIENTS=$3
C_LINES=100
if [ ! -z "$4" ]; then
C_LINES="$4"
fi
SUBJECT="Log Error! $LOGFILE"
tail -Fn0 "$LOGFILE" | while read line; do
echo $line | grep --quiet "$PATTERN"
if [ $? -eq 0 ]; then
# Search the file backwards.
# If there's a duplicate log entry we'll get the most recent one.
report=$(tail -n 1000 $LOGFILE | tac | grep -F -m 1 -C "$C_LINES" "$line" | tac)
echo "$report" | mail -s "$SUBJECT" "$RECIPIENTS"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment