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

Examples

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')
Copy

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

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')
Copy

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.

Related Tutorials

Code copied to clipboard successfully 👍