Let’s brighten the day, shall we?
In one of my previous posts, I explained how logging can be configured for TabPy: levels, the format of the message, where it is sent/stored, etc. Read here for more detail – How to Configure Logging in TabPy?
I also mentioned there is number of handlers from provided with Python (console, file, and others). But it is also possible to use third party or customized handlers. With this post, I am going to show how you can make console logging colorful with third-party formatter.
First, we need a formatter. You can choose any, I for the demonstration purposes picked up colorlog (https://pypi.org/project/colorlog/). The most important thing you need to pay attention to is how the formatter messages are formatted… Yes, you’ll need to define the format for the formatter. For the one I chose documentation for the format arguments is on the PyPi and GitHub (https://github.com/borntyping/python-colorlog) pages for the package.
Let’s install the package:
pip install colorlog
Next, we need a configuration file (additional reading – TabPy: modifying default configuration):
[loggers]
keys=root
[logger_root]
level=INFO
handlers=console
[handlers]
keys=console
[formatters]
keys=console
[handler_console]
class=StreamHandler
level=INFO
formatter=console
args=(sys.stderr,)
[formatter_console]
class=colorlog.ColoredFormatter
format=%(asctime)s [%(bold)s%(log_color)s%(levelname)-8s%(reset)s] %(log_color)s%(message)s%(reset)s
datefmt=%y/%m/%d %H:%M:%S
In the file everything till line 20 is standard: define loggers, handlers, and formatters. And now with the only formatter defined we want to use formatter from the package previously installed. The line class=colorlog.ColoredFormatter
tells Python logger to use specified formatter (ColoredFormatter
) from colorlog
package.
For the format
parameter which defines what will be in a logged message we use formatter specific arguments: %(bold)
makes text bold, %(log_color)
sets the color for following text, and %(reset)
changes text attributes to default. Again – for any other formatter you choose to use the arguments list most likely will be different.
Running TabPy with the config and querying it will look something like this: