Course map
Stage 1: Foundations
Stage 2: Data Integration
Stage 3: Building & Shipping
Stage 4: Customer Engagement
Stage 5: Specialization

Part 12 / Topic 3 of 7

Secrets in logs

Part 2 said "never log tokens"; this lesson makes it mechanical, because the discipline version fails the first time someone logs a full URL. A filter on the handler scrubs everything that passes through — including from child loggers and %s arguments:

# examples/02_keep_secrets_out_of_logs_with.py
import logging, re, sys

class SecretFilter(logging.Filter):
    PATTERN = re.compile(r"(Bearer\s+|token=|api_key=)[^\s&]+", re.IGNORECASE)
    def filter(self, record):
        # Redact the fully formatted message so values passed as %s arguments are covered too
        record.msg = self.PATTERN.sub(r"\1***", record.getMessage())
        record.args = None
        return True

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(levelname)s %(name)s %(message)s"))
handler.addFilter(SecretFilter())          # on the handler: also covers child loggers that propagate up
root = logging.getLogger("acme"); root.addHandler(handler); root.setLevel(logging.INFO)

root.info("calling https://api.acme.example/v1/shipments?token=abc123&page=2")
logging.getLogger("acme.client").info("header Authorization: %s", "Bearer acme-live-9f8e7d")
# INFO acme calling https://api.acme.example/v1/shipments?token=***&page=2
# INFO acme.client header Authorization: Bearer ***

Two details carry the example: the filter rewrites record.getMessage() (the formatted message), so secrets smuggled in as arguments are caught; and it sits on the handler, so acme.client — a child logger someone adds next month — is covered without knowing the filter exists. Belt and braces: the filter plus periodic log reviews, because the next secret will arrive in a shape your regex has not met.

🧪 Quick quiz

  1. A log line contains ?token=abc123. What should the logging setup do?
Show the answer

Mask it — e.g. token=***. The filter on the handler masked it, and a Bearer token passed as a %s argument from a child logger. (verified against the example output above)

Done here? The practice set for Part 12 — 4 exercises with solutions — is on the part page.

Search the guide