Mac Console - Coloring Specific Log Messages

2

2

I often use the Mac Console to monitor my web server logs. These logs are quite verbose, and it becomes difficult to scroll through them to monitor for errors.

Each message in the log has a format of [YYYY-MM-DD HH:MM:SS.sss] < INFO,WARN,ERROR > < Thread Name >

Is there any way I can set Console to color code the messages that have a Error tag? If not, what is the ideal way to sift through these logs? Note that it's often important to see what happened immediately before the error.

Ben Siver

Posted 2013-02-12T16:57:45.867

Reputation: 145

Answers

2

You can use Terminal and this shell function:

cless () 
{ 
   # less-like function that colors specified word
   # 'while read' reads every line and saves it to variable $REPLY
    while read; do
        # If line contains the word to highlight, grep with option --color...
        if [ $(echo $REPLY | grep -c $1) -eq 1 ]; then
            echo $REPLY | grep --color=always $1;
        else
        # ... otherwise simply output the line
            echo $REPLY;
        fi;
    # continue until end of file, paging with 'less'
    done < $2 | less -R
}

It takes two arguments, the word to highlight and the file to parse.

To use it, open Terminal in Applications>Utilties>Terminal and type;

$ function cless { while read; do if [ $(echo $REPLY | grep -c $1) -eq 1 ]; then echo $REPLY | grep --color=always $1; else echo $REPLY; fi; done < $2 | less -R; }
$ cless ERROR /path/to/my/logfile.log

As with less, use SPACE or F to scroll forward and B to scroll back. If the word you usually look for is ERROR, create an alias:

$ alias cerror='cless ERROR'
$ cerror /path/to/my/logfile.log

To load the function and alias automatically when you start Terminal, add these lines to your ~/.bashrc file:

function cless { while read; do if [ $(echo $REPLY | grep -c $1) -eq 1 ]; then echo $REPLY | grep --color=always $1; else echo $REPLY; fi; done < $2 | less -R; }
alias cerror='cless ERROR'

and reload it:

$ . ~/.bashrc

If you wish case-insensitive search, replace grep with grep -i (for instance, grep -c $1 would become grep -i -c $1).

jaume

Posted 2013-02-12T16:57:45.867

Reputation: 4 947