Python Logging - DEBUG Level


Python Logging - DEBUG Level

To log a debug line using Python Logging,

  • Check if the logger has atleast a logging level of DEBUG.
  • Use logging.debug() method, with the message passed as argument, to print the debug line to the console or file.

If logging level is set to DEBUG, then the logger will print to or write DEBUG lines to the console or log file.

If you set the logging level to INFO, WARNING, ERROR or CRITICAL, then the DEBUG lines will not be written to the log file.

The order of logging levels is:

DEBUG < INFO < WARNING < ERROR < CRITICAL

Examples

1. Log DEBUG lines

In this example, we will import logging module, set the level of the logger to DEBUG, and then use debug() method to log a DEBUG line.

Python Program

import logging

#create a logger
logger = logging.getLogger('mylogger')
#set logging level
logger.setLevel(logging.DEBUG)

handler = logging.FileHandler('mylog.log')
# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

#write a debug message
logger.debug('This is a DEBUG message')

After running the above program, in the mylog.log file, you could see the following content.

Log file - mylog.log

2019-02-25 22:31:40,353 - mylogger - DEBUG - This is an DEBUG message

2. Log only DEBUG lines using Python Logger

You can set filter to logger handler to log only DEBUG lines to the log file.

Python Program

import logging

class MyFilter(object):
    def __init__(self, level):
        self.__level = level

    def filter(self, logRecord):
        return logRecord.levelno <= self.__level

#create a logger
logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('mylog.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
#set filter to log only DEBUG lines
handler.addFilter(MyFilter(logging.DEBUG))
logger.addHandler(handler)

#write a debug line to log file
logger.debug('This is a DEBUG message')
logger.info('This is a INFO message')
logger.warning('This is a WARNING message')
logger.error('This is an ERROR message')
logger.critical('This is a CRITICAL message')

Console Output

2019-02-26 22:25:05,280 - mylogger - DEBUG - This is a DEBUG message

Only DEBUG message has been logged but no other messages that are INFO, WARNING, ERROR and CRITICAL.

Summary

In this tutorial of Python Examples, we learned how to use DEBUG level of Python Logging library.