Logging in Python
What is logging? Why is it required?
Logging is a means of tracking events that happen when some software runs.
Application development is a dynamic process, and therefore code improvisation requires iterations. It is difficult to handle all the use cases, and therefore many times we get to know about the exceptions only after the application is taken to production.
For updating the code, it is necessary to understand the flow of the application and pinpoint the point of error. This debugging process requires logging all the necessary checkpoints correctly, along with including exceptions wherever required for the debug purpose and identifying the failure points.
In local we may use print statements during the initial development phase, but as the complexity of the application increases, many modules may not work very well with the print statement.
How to do it in python?
Python has a built-in module logging which allows writing status messages to a file or any other output streams. The file can contain the information on which part of the code is executed and what problems have been arisen.
We have different logging levels in python
CRITICAL
ERROR
WARNING
INFO
DEBUG
We can set the logging level in python, the purpose of this level is two-fold:
It logs information with level tag, hence it is helpful in analysis and tracking
This level also helps in controlling the information we want to log
For example, if we set the log level to be WARNING, then it will log with a level warning or above it, it will not anything with level info or debug
Logs are time stamped.
Sample Code
Reference for Additional Reading
Last updated
Was this helpful?