Python Logging INFO Lines

Python Logging – INFO Level

To log an INFO line using Python Logging,

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

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

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

The order of logging levels is:

DEBUG < INFO < WARNING < ERROR < CRITICAL

Examples

1. Log INFO lines

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

Python Program

import logging

# Create a logger
logger = logging.getLogger('mylogger')

# Set logger level
logger.setLevel(logging.INFO)

# Or you can set the following level

# 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 info message
logger.info('This is an INFO message')
Copy

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

Log File – mylog.log

2019-02-25 22:30:36,695 - mylogger - INFO - This is an INFO message

2. Log only INFO lines using Python Logger

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

# Set filter to log only INFO lines
handler.addFilter(MyFilter(logging.INFO))
logger.addHandler(handler)

# Write an INFO line to log file
logger.info('This is a INFO message')
logger.warning('This is a WARNING message')
logger.error('This is an ERROR message')
logger.critical('This is a CRITICAL message')
Copy

Console Output

2019-02-26 22:22:31,134 - mylogger - INFO - This is a INFO message

Only INFO message has been logged, but not WARNING, ERROR and 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 👍