Adding color to your tail

Tail is a very useful tool for monitoring error stream. Sometime the output from tail can have too much information and its black and white monotone output can be hard to follow with the eyes.

The basic: Linux terminal has the capability to colorize text.
for example:
$ echo -e “Sample text nicely highlighted”
will produce a simple text saying, well:
Sample text nicely highlighted

But with some terminal color tagging such as:
$ echo -e “Sample \e[36mtext\e[0m nicely highlighted”
The \e above is identical with \033. I would suggest use \033 because it is safer to be used with a programming language such as PHP. PHP will not recognize \e but it will recognize \033, you’ll see below.
$ echo -e “Sample \033[36mtext\033[0m nicely highlighted”
Sample text nicely highlighted

Some basic coloring table can be seen here: http://www.bashguru.com/2010/01/shell-colors-colorizing-shell-scripts.html

Color Foreground Background
Black 30 40
Red 31 41
Green 32 42
Yellow 33 43
Blue 34 44
Magenta 35 45
Cyan 36 46
White 37 47

With the help of perl, which most likely comes with all linux distros, here is a way to colorize your tail output. Lets’ assume that every time you log something you will have a date-time prefixing your log. For example:

[22-Dec-2011 20:28:45] E_DATASOMETHING ……
Too much information …….
Too much information …….
[22-Dec-2011 20:28:46] E_FATAL Something
Too much information …….
Too much information …….
Too much information …….

Lets create a script that can colorize the date portion.
Create an executable linux bash file:


$ touch logwatch.sh
$ chmod 755 logwatch.sh
$ vim logwatch.sh

The copy and paste the following to your empty logwatch.sh

#!/bin/bash
vNow=$(date +"%d-%b-%Y")
tail -f ~username/errorlogfile.txt|perl -pe "s/$vNow/\e[1;30;32m$&\e[0m/g"

Voilà!

[22-Dec-2011 20:28:45] E_DATASOMETHING ……
Too much information …….
Too much information …….
[22-Dec-2011 20:28:46] E_FATAL Something
Too much information …….
Too much information …….
Too much information …….

If you need something more complex, say you want to highlight several words on the file you can use a scripting power of PHP, I’m rusty with my pearl.
Anyhow, save the script below as “colorize.php”, and you can have the words: blah, na, wa, and — highlighted on the fly!

$ tail -f test.txt|php colorize.php blah na wa --