Python Logging CRITICAL Lines

Python Logging – CRITICAL Level

To log a CRITICAL line using Python Logging,

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.

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us