Colored Logs for Python

Printing colored messages to the console

Colored Logs for Python
Adding some color to our console logs! (image by author)

Logging is an essential part of developing applications and lead to quick debugging and a broader understanding of what’s going on in your app. In this easy and short article we’re going to make our console logs a bit clearer by adding some color. Let’s code!


Preparations

We first need to install a packagepip install coloredlogs

Also make sure you understand the basics of logging and how to add a handler to your log with the article below:

Python logging — saving logs to a file & sending logs to an API
Get your logs to where they are needed to debug your code

Step 1: create a logger

Nothing new here: we just create a logger

We use the getLogger method so that we don’t use the root logger.

5 real handy python decorators for analyzing/debugging your code
Apply these handy, general-purpose decorators directly to your code

Step 2: coloredlogs

Here we install coloredlogs on our logger.

The last line makes sure that coloredlogs doesn’t pass our log events to the root logger. This prevents that we log every event double.


Step 3: creating a colored formatter

We want to add some style to our console outputs. We’ll define that here

Here you can add the style of the levels and all fields in the format.

Virtual environments for absolute beginners — what is it and how to create one (+ examples)
A deep dive into Python virtual environments, pip and avoiding entangled dependencies

Step 4: Create a colored stream handler

We’ll use a stream handler to print to our console. Well add the colored formatter to the handler so that it gets styled accordingly.


Step 5: Log and result!

Let’s put our logger to the test!

The beautiful results:

The result

Detecting motion with OpenCV — image analysis for beginners
How to detect and analyze moving objects with OpenCV

Conclusion

In this article we’ve gone through handlers for streams, files and http. There are some others that we haven’t handled like the socket handler, the SMTP handler. Because this article is already pretty lengthy I haven’t covered these in this article but maybe will in future ones so make sure to follow me.

I hope everything was as clear as I hope it to be but if this is not the case please let me know what I can do to clarify further. In the meantime, check out my other articles on all kinds of programming-related topics like these:

Happy coding!

— Mike

P.S: like what I’m doing? Follow me!

Join Medium with my referral link — Mike Huls
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…