Keep Secrets Out of Logs and Source
Core idea
Secrets such as credentials and tokens must be generated and stored appropriately, scoped to needed privileges and rotated when compromised. Use secrets rather than random for security-sensitive randomness. Retrieve production credentials through an approved secret provider. Log allowlisted event fields instead of full requests, headers or exception context that might include secrets.
import secretstoken = secrets.token_hex(16)print(len(token))print(all(c in '0123456789abcdef' for c in token))Sixteen random bytes are encoded as 32 hexadecimal characters. Only structural facts are printed. Choose entropy according to the threat model.
Expected output:
32TrueLog only selected fields
import logging, iostream = io.StringIO()logger = logging.getLogger('lesson')logger.propagate = Falsehandler = logging.StreamHandler(stream)logger.addHandler(handler)logger.setLevel(logging.INFO)request = {'id': 'r7', 'token': 'fake-secret'}logger.info('request=%s status=%s', request['id'], 'ok')print(stream.getvalue().strip())print(request['token'] in stream.getvalue())logger.removeHandler(handler)Only selected synthetic fields reach the log stream. No credential is printed.
Expected output:
request=r7 status=okFalseCommon mistake
Environment variables are not a universal secret vault; child processes, diagnostics and deployment tools may expose them. Avoid logging full dictionaries and rotate a leaked credential rather than merely deleting the log.
Practice
Write a logger test using a fake credential and assert it never appears in output. Identify where real secrets would be fetched and how access and rotation are handled.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Secrets and logging
Check your understanding of secrets and logging.
What is printed?
import secretsprint(len(secrets.token_bytes(8)))What is printed?
row={"id":"r1","secret":"fake"}print({"id":row["id"]})What is preferred for security-sensitive random tokens?
What is required after a credential is exposed?