Ken Chen
Ken Chen

Reputation: 3

Monitoring/highlighting terminal stdout for keywords

Because our recent development work, I was put into a position where I have to monitoring a few of our application's output logs, specifically I am looking for a certain error code(s). Because my limited scripting skill right now the only thing I can do is to tail -f the log file and just keep looking for update. I also use PuTTY. I am hoping someone can make a few suggestions on how I can accomplish either one of the following, if possible:

  1. Modify bash.rc so when certain keyword(s) displayed in terminal they will be highlighted
  2. Utilize PuTTY's audio/visual bell so whenever a keyword is displayed alert will go off

Upvotes: 0

Views: 676

Answers (2)

yatsek
yatsek

Reputation: 1015

It's weird that this not was answered completely taking into consideration that @bjarneh presented almost final solution.

So for the sake of other people coming here from search engines - here it is.

To achieve colored text in the terminal it's necessary to use ANSI color codes.

Like in this example:

echo -e "\e[$3{COLOR_CODE};1mMy colored text\e[0m"

Where ${COLOR_CODE} can be a number from 1 to 6, but base is:

  • 1 - red
  • 2 - green
  • 4 - blue

Other colors can be achieved by adding those components together - like 3 - yellow, 5 - magenta, 6 - cyan. Whole sequence - for example \e[31;1m - is an ANSI terminal color code. Similarly \e[0m is an ANSI terminal code, but this one "resets" all text attributes, and stop coloring text.

How to achieve colors with sed? There needs to be an "escape" sequence present. echo -e replaces \e for specific binary code. To do this in sed \x1b is needed.

So - to color any text from stdout of any application use following snippet:

COLOR_CODE=1 #red
tail -f somefile.log | sed s/keyword/\x1b[3${COLOR_CODE};1m\0\x1b[0m/g"

You can also chain coloring, and use more complex regex:

WARNING_COLOR=3 #yellow
ERROR_COLOR=1 #red
tail -f somefile.log | sed -e "s/warning/\x1b[3${WARNING_COLOR};1m\0\x1b[0m/Ig" \
-e "s/\(error\|fault\)/\x1b[3${ERROR_COLOR};1m\1\x1b[0m/Ig"

Obviously there are more ANSI color sequences, but use this just as an example.

Upvotes: 0

bjarneh
bjarneh

Reputation: 618

coloring your output could be done by just adding a sed regexp to your tail -f, i.e.

tail -f somefile.log | sed 's/keyword/highligtedkeyword/g'

just add some escape sequences for color..the bell part i'm not really sure about..

Upvotes: 0

Related Questions