Python Logging WARNING Lines

Python Logging – WARNING Level

To log an INFO line using Python Logging,

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

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

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

The order of logging levels is:

DEBUG < INFO < WARNING < ERROR < CRITICAL

Example 1: Log WARNING lines

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

Python Program

import logging

#create a logger
logger = logging.getLogger('mylogger')
#set logger level
logger.setLevel(logging.WARNING)
#or you can set one of the following level
#logger.setLevel(logging.INFO)
#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 Warning message
logger.warning('This is a WARNING 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:27:00,071 - mylogger - WARNING - This is an WARNING message

Example 2: Log only WARNING Lines using Python Logger

You can set filter to logger handler to log only WARNING 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.WARNING)
handler = logging.FileHandler('mylog.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
#set filter to log only WARNING lines
handler.addFilter(MyFilter(logging.WARNING))
logger.addHandler(handler)

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:20:28,332 - mylogger - WARNING - This is a WARNING message

Only WARNING message has been logged, but not ERROR and CRITICAL.

Summary

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