How to tail logs with syntax highlighting

Picking out data in text-based logs can be frustrating.

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

#!/usr/bin/env bash

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/'

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

Personally, I name the script and I make a shell alias to it.

alias tailc="<your-path-to>/"

To execute:

tailc -f /path/to/file.log


If you're using logs mostly as a way to read stacktraces, frameworks often break the general rule of 1 log item per newline, so we can also grey out all the excess:

    # ...
    # lines that start with "#"
    -e 's/\(\#.*\)/\o033[90m\1\o033[39m/' \

    # lines that have "stacktrace" in them
    -e 's/\(stacktrace\)/\o033[37m\1\o033[39m/'

Colors for the command line can be finnicky, so if the listed colors aren't to your liking, you'll probably have to adjust the color sequences.