Python Loggging - INFO Level
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')
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')
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.