Colored Logs for Python
Printing colored messages to the console
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:
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.
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.
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:
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:
- Cython for absolute beginners — 30x faster code in two simple steps
- Why Python is so slow and how to speed it up
- Git for absolute beginners: understanding Git with the help of a video game
- Simple trick to work with relative paths in Python
- Docker for absolute beginners: the difference between an image and a container
- Docker for absolute beginners — what is Docker and how to use it (+ examples)
- Virtual environments for absolute beginners — what is it and how to create one (+ examples)
- Create and publish your own Python package
- Create a fast auto-documented, maintainable, and easy-to-use Python API in 5 lines of code with FastAPI
Happy coding!
— Mike
P.S: like what I’m doing? Follow me!