Tailing the Apache Access Log

Header image. Sniper in a field looking at a target. Symbolizes a hunter tailing Apache log.

As a system administrator it is sometimes useful to watch things happening live in Apache access log. Tail would be the command usually used to accomplish the task, while logged in as an appropriate user through a secure shell session. Tailing the Apache Access Log was a resolution to a problem that I encountered when doing so, i.e. timeout of the secure shell session.

Having the secure shell timeout is a good thing. And it’s default timeout is probably something we shouldn’t be messing with for other than a good reason. IT wisdom says monitoring a log is not a good enough reason, IMHO. And regardless, this is only a problem that you’ll have at odd hours or on a low traffic site. While this script may be of limited usefulness on high traffic commercial sites, it can be adapted to other uses.

This post is part of the Bash scripts for fun and leisure series.

The Script for Apache Access Log Tailing

I called this script tail-loop.sh. It executes an infinite loop which requires Ctrl-C to exit. It’s only purpose is to stop the secure shell from timing out while watching the access log.

#! /bin/bash
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NORM='\033[0;0m'
LOOPCOUNT=0
while true
do
	echo -e $GREEN'LOOP '$((++LOOPCOUNT))'! '`date +"%D %T"`' ----------------'$NORM
	timeout --foreground --signal=SIGKILL --kill-after=1.0s 5.0m tail -f /var/log/apache2/access.log
done

Everything is visual fluff except the timeout command which calls the tail -f command on the Apache access log. The loop time is five minutes and timeout will terminate tail, which then causes the next cycle of do and done.

There is a lot more visual fluff and logic that could be added. One possibility is changing the color of lines that fulfill the regular expression “\ [34][01]. The use of that regular expression finds entries of interest in Apache access log, such as redirects and client errors.

When tailing the Apache access log, please make sure you read the timeout and tail man pages. You will have to play around with the loop time so that it works for you. That is better than adjusting the secure shell idle timeout time, IMHO.

Safe computing, folks! If you add some spiffy code please remember to pay it forward and share!