Python includes a useful logging module within its standard library that allows for each event within an application to be logged and tracked. By logging messages, we can easily debug our software and investigate events during the development, testing, and production phases.
We could print messages to the console, but this can quickly add clutter to our code. The more complex the application, the more difficult it can be to know where a print statement originated. There is also a chance that some print statements could be left behind and not removed once the application goes into a production-ready state. Using the logging module allows us to write clean and maintainable code that can be easily debugged, tracked, and supported by other developers down the road.
The logging module provides several formatting options that make logged messages very easy to read. While print statements can be formatted, it is not as simple and fast compared to using the logging module. Cleanly formatted log messages can help troubleshoot issues in the application and also help future developers with debugging who may work on the application.
Let’s investigate the advantages of using the logging module with an example.
Imagine you frequently travel out of the country and develop an application to convert currencies between countries quickly.
View the file with_printouts.py and compare it to the file with_logging.py. Examine the differences in readability, clean lines of code, simplicity, and reduction of repeated code.
Now, execute the with_printouts.py code by clicking Run while you have the file open.
Now, execute the with_logging.py code. Examine the differences in output in terms of readability of the printout/logged messages and the detailed information that is provided in the messages between this output and the previous with_printouts.py output.
Imagine you only want to view
ERROR related printout/logged messages. Consider how this can be accomplished quickly without having to remove several
logging module! Let’s introduce how. Click Run to move onto the next exercise!