Skip to content

Instantly share code, notes, and snippets.

@krinkere
Last active March 9, 2017 02:55
Show Gist options
  • Save krinkere/ba33342797de7773cfa82fce5dd811bf to your computer and use it in GitHub Desktop.
Save krinkere/ba33342797de7773cfa82fce5dd811bf to your computer and use it in GitHub Desktop.
Example of adding a filter to a Logger's Handler. Enables messages at one specifie level only
"""
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment