Most of the solutions on this page add the color codes to the logfile as it is generated. That has some problems:
- If you are later grepping through the log, you'll have to remember to account for the color codes in your grep patterns. (e.g. "grep "ERROR " won't find lines in which the error is highlighted red.)
- It can only work on the logfiles you are producing yourself, and that you take the trouble to add color codes to.
Instead, this solution adds color as the logfiles is viewed, meaning it can be used on any logfile, no matter where they came from, and they leave the original logfile unmolested, so traditional tools like grep don't get confused by any color codes embedded in the log text.
Better yet, it works for coloring all sorts of text, not just logfiles.
A simple but very flexible tool for coloring ANY terminal text is 'colout'.
pip install colout
myprocess | colout REGEX_WITH_GROUPS color1,color2...
Where any text in the output of 'myprocess' which matches group 1 of the regex will be colored with color1, group 2 with color2, etc.
tail -f /var/log/mylogfile | colout '^(\w+ \d+ [\d:]+)|(\w+\.py:\d+ .+\(\)): (.+)$' white,black,cyan bold,bold,normal
i.e. the first regex group (parens) matches the initial date in the logfile, the second group matches a python filename, line number and function name, and the third group matches the log message that comes after that. This looks like:
(This example also uses a sequence of 'bold/normals' as well as the sequence of colors)
Note that lines or parts of lines which don't match any of my regex are still echoed, so this isn't like 'grep --color' - nothing is filtered out of the output.
Obviously this is flexible enough that you can use it with any process, not just tailing logfiles. I usually just whip up a new regex on the fly any time I want to colorize something. For this reason, I prefer colout to any custom logfile-coloring tool, because I only need to learn one tool, regardless of what I'm coloring: logging, test output, syntax highlighting snippets of code in the terminal, etc.