Python Logging ERROR Lines

Python Logging – ERROR Level

To log an ERROR line using Python Logging,

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

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

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

The order of logging levels is:

DEBUG < INFO < WARNING < ERROR < CRITICAL

Example 1: Log ERROR lines

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

Python Program

import logging

#create a logger
logger = logging.getLogger('mylogger')
#set logger level
logger.setLevel(logging.ERROR)
#or set one of the following level
#logger.setLevel(logging.WARNING)
#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 error message
logger.error('This is an ERROR message')

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

Log File – mylog.file

2019-02-25 22:25:12,473 - mylogger - ERROR - This is an ERROR message

Example 2: Log only ERROR Lines using Python Logger

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

logger.error('This is an ERROR message')
logger.critical('This is an CRITICAL message')

Console Output

2019-02-26 22:13:28,896 - mylogger - ERROR - This is an ERROR message

Only ERROR level message has been logged, but not CRITICAL.

Summary

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