Skip to content

Instantly share code, notes, and snippets.

@elmotec
Created February 16, 2014 03:10
Show Gist options
  • Save elmotec/9028702 to your computer and use it in GitHub Desktop.
Save elmotec/9028702 to your computer and use it in GitHub Desktop.
def filter_log(msg_re=''):
"""Decorator to temporarily disable logging so as to prevent noise.
:param msg_re: regular expression to be filtered out.
:type msg_re: string.
Note that the default argument '' causes all warnings to be filtered out.
"""
def decorator(func):
"""helper function returned by the decorator."""
class MessageFilter(logging.Filter): # pylint: disable=R0903
"""Filters logging."""
def filter(self, record):
message = record.getMessage()
return re.match(msg_re, message) is None
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Wraps the target function/method with temporary filter."""
msg_filter = MessageFilter()
try:
estimate.log.addFilter(msg_filter)
return func(*args, **kwargs)
finally:
estimate.log.removeFilter(msg_filter)
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment