How can I color Python logging output?
Add some color to your Python logging output by creating a custom Formatter subclass, using ANSI escape codes to change text colors:
The code directly integrates color information into the logging output so it's easier to distinguish between different logging levels.
Make it work everywhere: Cross-platform compatibility
Beat Windows at its own game
While ANSI escape codes add a bit of spice to your console output, they don't always get along with Windows terminals right off the bat. To make sure everyone can join the color party, use the colorama
module:
Don't forget to kick-start colorama.init()
at the beginning of your script to set up ANSI escape code emulation on Windows.
Outsource the work: Plug-and-play solutions
When in doubt, colorlog it out
If you want a ready-to-use solution that offers customization options, roll out the red carpet for colorlog
:
-
Install
colorlog
:pip install colorlog
-
Set up a
ColoredFormatter
withcolorlog
:
colorlog
takes on the heavy lifting of managing color mapping and gracefully shifts gears to non-colored output for color-blind terminals.
Show your true colors: Customize log levels
Light up each log level with unique colors. Use logging.addLevelName()
to color-code your logs:
Pull out the big guns: Advanced logging features
Custom logger class for the win
If you're working on something where multipurpose logging is essential, it's time to create a custom logger class. Setting up multiple handlers with diverse formats becomes a cakewalk:
Use actively-maintained libraries
Make it a point to choose libraries that are maintained regularly for continual compatibility and updates. Libraries like colorlog
and Rich offer not just color logging but also varied formatting options.
Structure your logs
When crafting your log format, include essentials like timestamps, file names, function names for a convenient bird's eye view of your application's workings:
Preconfigured formats give you a ton of valuable data without bombarding you with irrelevant details.
Expand your arsenal: Explore alternative tools
Sometimes, third-party libraries can offer additional functionalities on top of Python's logging module. The Rich library, for example, offers table rendering, progress bars, and markdown support, all of which can seriously level up your debugging and monitoring game.
To use Rich for logging:
-
Install Rich:
pip install rich
-
Set up Rich logging:
Using Rich can give your logs a sophisticated touch with minimal configuration.
Was this article helpful?