How do you avoid leaking secrets into logs?
AdvancedConceptExceptions, context managers, files & logging
Answer
- Never log whole request objects, headers, environment dumps or config dicts.
- Wrap secrets in a type whose
__repr__and__str__return"****"(pydantic'sSecretStrdoes this). - Add a
logging.Filterthat redacts patterns (AKIA[0-9A-Z]{16},Bearer \S+,password=\S+) as a safety net. - Keep urllib3/botocore at WARNING in production; DEBUG for botocore logs full request bodies.
- Mask in CI (
::add-mask::in GitHub Actions).
Redaction filters are a backstop, not the control. The control is not logging the value at all.
More on Exceptions, context managers, files & logging
How does `try` / `except` / `else` / `finally` work?BeginnerWhy is a bare `except:` (or `except Exception: pass`) dangerous?BeginnerWhat is exception chaining, and what is `raise ... from`?IntermediateWhen should you define custom exception classes?IntermediateWhat is the EAFP vs LBYL style, and which does Python prefer?IntermediateHow does a `with` statement work, and why use it for files?Beginner