Member-only story
Python Logging for Absolute Beginners
Stop using print statements for debugging and switch to something more advanced
Logging is essential to understanding what happens in your application, why it happens and when it happens. Not only can you catch errors more easily, debugging becomes much faster as well since you have a nice cookie crumb trail that leads you right to the problem.
No only does logging make developing and debugging more easy, there are many other advantages which we’ll get into in this article. Let’s code!
But first
Let’s first understand logging by comparing it to the most-used way of debugging Python code: just using print()
statements. In short: logging offers all that just printing offers and much more. Let’s go through the main advantages of why logging is better than printing.
Setting the importance — execute in debug mode
There are 5 main types of logging that all have a different level of importance
- debug
- info
- warning
- error
- critical
So in stead of print(somevalue)
you can logger.debug(somevalue)
or logger.error(somevalue)
. You can set a logger level application-wide. This means that if you set your logger to the warning
level, it will only handle warning
logs and all above, ignoring lower importance levels like logger.debug()
and logger.info()
statements.
The biggest advantage of this is that you can start up your application in debug-mode, where the logger is set to the lowest (debug
) level. Then you’ll see everything that happens in your app, making development and debugging much easier. Once your code is ready for production you can just set your logger to the error
-level, for example, to only catch the severe logs.
Additional information — metadata
Logging provides more information. Imagine you log an error. In addition to just printing the error message you can add all kinds of metadata that lead you straight to the error:
- datetime
- filename and path of…