Wednesday, March 8, 2017

Example of adding a filter to a Logger's Handler.

Awesome example developed during my Advanced Python Training that shows how to log to a different log file based on log level

"""
Example of adding a filter to a Logger's Handler.
"""
from logging import getLogger, FileHandler, INFO, ERROR


class LogOneLevel:
  """Enables messages at one specifie level only"""

  def __init__(self, level):
      self.level = level

  def filter(self, log_record):
      return log_record.levelno == self.level

logger = getLogger('logger_demo')

info_handler = FileHandler('info.log')
info_handler.addFilter(LogOneLevel(INFO))  # add filter to handler
logger.addHandler(info_handler)

error_handler = FileHandler('error.log')
error_handler.addFilter(LogOneLevel(ERROR))  # add filter to handler
logger.addHandler(error_handler)

logger.info("info msg")    # written to info.log only
logger.error("error msg")  # written to error.log only

File-Based Configuration

1. Define a Handler subclass that adds a Filter instance to itself:

class InfoHandler(RotatingFileHandler):
   def __init__(self, *args, **kwargs):
       super().__init__(self, *args, **kwargs)
       self.addFilter(LogOneLevel(INFO))

2. Configure Handler subclass in config file:

[logger_unittestgui]
level=DEBUG
handlers=console_handler,info_handler

[handler_info_handler]
class=mypackage.mylogging.InfoHandler
formatter=file_formatter
args=('gui.log', 'a', 10000000, 5)  # passed to superclass __init__()


# http://tinyurl.com/logging-filter

No comments:

Post a Comment