Python Logging

Atm Ahad
Big0one
Published in
4 min readJul 20, 2020

Consider a scenario of running your program and it crashes. There is hardly a very little chance that you detect the cause of the problem. And if you detect the cause, it may consume a lot of time. You can put this load on something called logger. Logging is a means of tracking events that happen when some software runs. With logging, if something goes wrong, we can determine the cause of the problem. Logging is important for software developing, debugging and running. It can help you develop a better understanding of the flow of a program and discover scenarios that you might not even have thought of while developing. Logs provide developers with an extra set of eyes that are constantly looking at the flow that an application is going through.

Printing or Logging

Some developers use the concept of printing the statements to validate if the statements are executed correctly or some error has occurred. It may solve your issues for simple scripts but for complex scripts, printing approach will fail. So, printing is not a good idea. Python provides a logging system as a part of its standard library, so you can quickly add logging to your application which allows writing status messages to a file or any other output streams.

Adding logging to your Python program is as easy as this:

import logging

With the logging module imported, you can use something called a “logger” to log messages that you want to see. By default, there are 5 standard levels indicating the severity of events.

Debug : These are used to give Detailed information, typically of interest only when diagnosing problems.

Info : These are used to Confirm that things are working as expected

Warning : These are used an indication that something unexpected happened, or indicative of some problem in the near future

Error : This tells that due to a more serious problem, the software has not been able to perform some function

Critical : This tells serious error, indicating that the program itself may be unable to continue running

The corresponding methods for each level can be called as shown in the following example:

import logginglogging.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')

The output would look like this:

Notice that the debug() and info() messages didn’t get logged. This is because, by default, the logging module logs the messages with a severity level of WARNING or above. You can change that by configuring the logging module to log events of all levels if you want. You can also define your own severity levels by changing configurations, but it is generally not recommended.

Formatting the log message

You can pass any variable that can be represented as a string from your program as a message to your logs. f you want to log the process ID along with the level and message, you can do like this:

import logginglogging.basicConfig(format='%(process)d-%(levelname)s-%(message)s')
logging.warning('This is warning')

Resulting output like this-

Another example where you can add the date and time info:

import logginglogging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
logging.info('Admin logged in')

Now, you may want to include dynamic information from your application in the logs.

import loggingname = 'Joe'
logging.error(' %s raised an error',name)

The logging module also allows you to capture the full stack traces in an application. Exception information can be captured if the exc_info parameter is passed as True-

import logginga = 5
b = 0
try:
c = a/b
except Exception as e:
logging.error('Exception occured',exc_info=True)

If exc_info is not set True, the log record would not tell anything about the exception.

In a real-world scenario, the exception might not be as simple as a ZeroDivisionError. Debugging an error in a complicated codebase with a log can save developer’s life.

Thankful To-

--

--