log file monitoring using tail -f, (n)awk, mailx and xmessage

From time to time, I would like to monitor one or more of my log files, e.g. the web server’s access log.

Here’s a short script that I use for monitoring the apache log. It:

  1. sends an email (via mailx)
  2. creates a popup window (via xmessage)

For the popup window to be created, the X server must be allowed to display the application, using xauth or xhost. Instead of xmessage, you may also use zenity (which comes with Solaris).
Don’t forget to customize the recipient’s email address (RECIPIENT) and the name of the file that is to be monitored (FILE_TO_MONITOR) before using the script!

The Script

# monitor-apache-log: notify when new entries in apache log matches search string
# notification by email and xmessage popup
# email subject contains all relevant information - see below
# argument: string to search for in the log file
# customize:
# end of customization
# access_log fields used:
# $1      = IP address of client
# $(NF-3) = name of file
# $NF     = size of file
# prepend \ before any / so the search string can be used in (n)awk even if it contains "/":
SEARCH_STRING=$(echo $1 | nawk '{gsub ("/", "\\/"); printf ("%s", $0)}')
tail -f ${FILE_TO_MONITOR} | \
nawk '/'${SEARCH_STRING}'/{system ("echo \"\"|mailx -s \""$1" "$(NF-3)" "$NF"\" '${RECIPIENT}'; xmessage -geometry 800x200 -bg red -fn \"-adobe-helvetica-bold-r-*-*-18-*-100-100-p-*-iso8859-1\" -nearmouse \""$1" "$(NF-3)" "$NF"\" &")}'

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: