How would you write a custom logging.Filter to redact sensitive data like passwords from log messages?
Short answer
A Filter subclass implements filter(self, record), which can inspect and modify record.msg or record.args in place before returning True (keep the record) or False (drop it).
Advertisement
AModel answer
A Filter subclass implements filter(self, record), which can inspect and modify record.msg or record.args in place before returning True (keep the record) or False (drop it). Attaching this filter to a handler or logger lets you scrub sensitive patterns (like passwords or credit card numbers) from every message that passes through, centrally rather than at every call site.
import logging, re
class RedactFilter(logging.Filter):
def filter(self, record):
record.msg = re.sub(r'password=\S+', 'password=***', str(record.msg))
return True
logger = logging.getLogger('app')
logger.addFilter(RedactFilter())
logger.info('Login attempt password=hunter2') # logs 'password=***'Real-world example
A compliance-sensitive fintech application attaches a redaction Filter to all handlers to guarantee PII never lands in log files, satisfying an audit requirement.
Likely follow-ups
- Should redaction happen at the Filter level or at the call site?
- How do you test that a Filter catches all sensitive patterns?
Related topics