Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.