How to tail logs with syntax highlighting

If you ever end up tailing and scanning logs/stacktraces for more than 15 minutes, it can be annoying to pick out the relevant pieces while looking at a wall of text.

Jumping on the back of this response we can quickly make a script to set some appropriate syntax highlighting based on log levels!

#!/bin/sh

tail ${@:1} | sed --unbuffered \
    -e 's/\(.*INFO.*\)/\o033[90m\1\o033[39m/' \
    -e 's/\(.*NOTICE.*\)/\o033[37m\1\o033[39m/' \
    -e 's/\(.*WARNING.*\)/\o033[33m\1\o033[39m/' \
    -e 's/\(.*ERROR.*\)/\o033[93m\1\o033[39m/' \
    -e 's/\(.*CRITICAL.*\)/\o033[31m\1\o033[39m/' \
    -e 's/\(.*ALERT.*\)/\o033[91m\1\o033[39m/' \
    -e 's/\(.*EMERGENCY.*\)/\o033[95m\1\o033[39m/'

Personally I make an alias alias tailc="<path>/tailc.sh", and then execute with tailc -f /path/to/file.log.

log-levels

If you’re using logs mostly as a way to read errors/stacktraces in dev, frameworks often break the general rule of 1 log item per newline, so by default, let’s grey out all the trash:

@@
#!/bin/sh

tail ${@:1} | sed --unbuffered \
    -e 's/\(.*INFO.*\)/\o033[90m\1\o033[39m/' \
    -e 's/\(.*NOTICE.*\)/\o033[37m\1\o033[39m/' \
    -e 's/\(.*WARNING.*\)/\o033[33m\1\o033[39m/' \
    -e 's/\(.*ERROR.*\)/\o033[93m\1\o033[39m/' \
    -e 's/\(.*CRITICAL.*\)/\o033[31m\1\o033[39m/' \
    -e 's/\(.*ALERT.*\)/\o033[91m\1\o033[39m/' \
    -e 's/\(.*EMERGENCY.*\)/\o033[95m\1\o033[39m/' \
+    -e 's/\(\#.*\)/\o033[90m\1\o033[39m/' \ # lines that start with "#"
+    -e 's/\(stacktrace\)/\o033[37m\1\o033[39m/' # lines that have "stacktrace" in them

Note: These regexes are specifically for a Monolog stacktrace. You may have to adjust them depending on how your framework/logger formats stacktraces.