Whenever we build a software and run it, there may arise some errors or exceptions which hinder the normal execution of the software. Logging helps us to keep the track of the events which takes place when a software is running. Logging is normally useful in software development process especially debugging and running. If we have no logging facility, and our program crashes, it will be very difficult for us to identify the cause of the problem. We may be able to figure out the problem in small programs but in real world, there are complex programs, so it is near to impossible to figure out the issues manually. If possible, it is much time consuming.
Python has an in-built logging module for our use which solves this problem of ours. Logging is a very useful tool. It helps us get a better understanding of the flow of the program and informs us of the problems or scenarios which we may not have thought while developing process.
Python has the logging module ready for our use. We just need to import it into our programs, which is done as shown below
The logging module helps us to write status messages to a file or other output streams. The file can contain other information including, which part of the code is executed and what problems have arisen.
With logging module, we can use “logger” to log messages which we want to see. By default, there are 5 levels of log messages which depict severity of the events.
The following are the 5 levels in increasing order of the severity.
DEBUG − This is used to give detailing information; it is used when diagnosing problems.
INFO − Used to confirm that things are working correctly as expected.
WARNING − As the name suggests, it is used to give some message which informs us of an issue which can cause problems in future.
ERROR − Used to give an error message, that the application or software has failed to perform some function.
CRITICAL − This informs of a serious problem indicating that the program may stop performing.
The logging module provides us with a default logger, which allows us to proceed without much configuration.
import logging logging.debug('This is a debug message') logging.info('This is an info message') logging.warning('This is a warning message') logging.error('This is an error message') logging.critical('This is a critical message')
WARNING:root:This is a warning message ERROR:root:This is an error message CRITICAL:root:This is a critical message
Note: The info() and debug() messages are not loaded. This is because by default, the logger loads the messages of severity warning and higher. So if you need log messages of all severities to be loaded, you need to configure the logger manually.