Python logging: stop using print in your Python code for logging, use the logging module like a pro
Let’s use logging in Python from now on
--
When we write Python programs, we often need to print out the results and also log some exceptions. As a beginner, we would normally use the print
function to log everything. It is handy to use the print
command but the logs are not stored properly and are difficult to check sometime after the program is finished.
As a best practice for logging in Python, we should use the built-in logging module. With the logging module, we can log different levels of messages to different destinations. We can also configure the log messages to be sent to some channels so that we can get notified when some errors occur. In this article, the logging module is introduced in detail and you will learn how to use the logging module like a pro step by step.
First, let’s log a warning message with the logging module:
>>> import logging
>>> logging.warning("This is a warning!")
WARNING:root:This is a warning!
We can see that the warning is logged in the terminal.
Now Let’s try to log a piece of information:
>>> logging.info("This is some information.")
This time nothing is logged. This is an important reason why some beginners think the logging module is difficult to use since they can’t get what they want. They get frustrated with the logging module and turn to use the print
function instead which always gives them what they want.
Actually, this problem is related to the log level of the logging module, which is a fundamental issue for logging in Python. If you understand the log levels, you can use the logging module proficiently and can always get what you want.
There are five log levels in the logging module, namely DEBUG, INFO, WARNING, ERROR, and CRITICAL, which can be logged with the corresponding lower case functions debug
, info
, warning
, error
, and critical
, respectively. The default level is WARNING, which means that only events of this level and above will be logged. This is the reason why we can see the logging of a warning, but not the logging of an info.