Logging CRITICAL Lines in Python - Examples


Python Logging - CRITICAL Level

To log a CRITICAL line using Python Logging,

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

If logging level is set to DEBUG, INFO, WARNING, ERROR or CRITICAL, then the logger will print to or write CRITICAL 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 CRITICAL lines

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

Python Program

import logging

#create a logger
logger = logging.getLogger('mylogger')
#set logger level
logger.setLevel(logging.CRITICAL)
#or set one of the following level
#logger.setLevel(logging.ERROR)
#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 critical message
logger.critical('This is an CRITICAL 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:21:46,087 - mylogger - CRITICAL - This is a CRITICAL message

Summary

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