Sub topic 7
Keeping credentials out of logs
This chapter assumes you can call an LLM API from Python, know how application logging and log levels work, and can read a basic regular expression. It covers how credentials leak into logs, how to stop each leak at its source, and how to test that the fixes hold.
Why credentials are the worst thing to leak
A prompt that contains personal data is a privacy problem. A leaked API key is an access problem. Anyone who reads the key can call the model as you, run up your bill, and read any data your account can reach. Logs are often copied to many places: a log aggregator, a ticketing system, a chat thread pasted during an incident. A key written once may end up in all of them.
Redaction of logged text (covered in the next chapter) is a safety net. For credentials, the stronger approach is to never put them near the logging code at all. Redaction by pattern can miss a key that has an unusual shape. A key that was never logged cannot be missed.
Where credentials leak
Credentials rarely reach logs because someone wrote logger.info(api_key). They arrive indirectly. These are the common routes.
| Route | How it happens | Example |
|---|---|---|
| Request headers | A debug log dumps the full HTTP request | `Authorization: Bearer sk-...` |
| Client objects | A client is logged with `repr()` or `%r` and its fields include the key | `Client(api_key='sk-...')` |
| Exception messages | An error string includes the URL, headers, or configuration | `ConnectionError: ... key=sk-...` |
| Query strings | Some APIs accept the key as a URL parameter, and URLs get logged | `https://api.example.com/v1?key=...` |
| Configuration dumps | Startup code logs all settings or all environment variables | `logger.info(os.environ)` |
| Prompts and responses | A user pastes a key into a chat, or the model repeats one from context | "Here is my token: ..." |
| Tracebacks | A framework prints local variables in the stack trace | Debug-mode error pages |
The last two routes matter for LLM work in particular. Users paste secrets into prompts, and a model that sees a secret in its context can echo it in its answer. This means credentials can enter your logs through content as well as through your own configuration.
Control 1: Load credentials from outside the code
Keep keys out of source files and out of the repository. Read them from environment variables or a secret manager when the process starts. This does not stop log leaks directly, but it removes one major source: keys committed to code often get logged as part of a config object, and they also end up in version history.
import os
def load_api_key() -> str:
key = os.environ.get("LLM_API_KEY")
if not key:
raise RuntimeError("LLM_API_KEY is not set")
return keyThe error message names the variable, not its value. Make that a habit. An error that says what is missing is useful. An error that echoes the whole configuration is a leak.
Control 2: Wrap secrets so they cannot print
The most reliable protection inside your own code is a type that refuses to show its value. If the key is held in such an object, then print, repr, f-strings, and logging format calls all show a mask instead.
class Secret:
"""Holds a credential and hides it from str() and repr()."""
__slots__ = ("_value",)
def __init__(self, value: str):
self._value = value
def reveal(self) -> str:
return self._value
def __repr__(self) -> str:
return "Secret('***')"
__str__ = __repr__
api_key = Secret("sk-abcdefghijklmnop1234")
print(api_key)
print(f"client config: key={api_key!r}")Output:
Secret('***')
client config: key=Secret('***')Only code that calls reveal() sees the real value, and that should be a single place: the function that builds the request headers. A search for reveal( then shows every spot where the key is exposed, which makes review easy.
Two limits apply. First, __slots__ and a masked repr stop accidental printing, not a determined reader: any code in the process can still call reveal(). Second, the wrapper does not help once the real string has been copied into a header dictionary, so keep that dictionary out of logs too (see the next control).
Libraries such as Pydantic offer a comparable SecretStr type if you already use that library for settings. It masks the value in the same way.
Control 3: Never log headers or raw requests wholesale
Log the fields you chose, not the object that holds them. Compare these two lines.
# Risky: dumps everything the library knows about the request
logger.debug("request: %s", request.__dict__)
# Safer: names exactly what is logged
logger.info("llm_call model=%s prompt_chars=%d", model, len(prompt))This follows the policy from earlier chapters: metadata by default. A field you did not name cannot leak. If you must log headers for debugging, use an allowlist of header names that are known to be harmless.
SAFE_HEADERS = {"content-type", "content-length", "x-request-id", "retry-after"}
def safe_headers(headers: dict) -> dict:
return {k: v for k, v in headers.items() if k.lower() in SAFE_HEADERS}An allowlist fails safe. A new header added by a proxy, such as X-Api-Key or Cookie, is dropped until someone decides it is harmless. A denylist fails the other way: it logs everything you forgot to list.
Control 4: Turn down the chatty libraries
HTTP client libraries and some SDKs write headers and bodies to their own loggers at DEBUG level. Setting your root logger to DEBUG during an investigation can switch these on without anyone noticing, and the output includes the Authorization header.
Set an explicit level for the libraries you use.
import logging
logging.basicConfig(level=logging.INFO)
# Libraries that can print request details at DEBUG
for name in ("urllib3", "httpx", "httpcore", "openai", "anthropic"):
logging.getLogger(name).setLevel(logging.WARNING)Check which loggers your own stack uses rather than copying this list. You can list active loggers with logging.root.manager.loggerDict. Apply the setting after any code that reconfigures logging, because some frameworks reset levels when they start.
Control 5: Scrub exceptions
Exception messages are written by library authors, and some include a URL with a key in the query string or a copy of the failing request. Two defenses work together.
- Log the exception type and a short, controlled message, not the full string. The wrapper from the metadata chapter logs
type(exc).__name__for this reason. - If you need the message, pass it through the same redaction used for content before it is logged.
def safe_error(exc: Exception) -> dict:
return {
"error_type": type(exc).__name__,
"error_message": redact(str(exc))[:300],
}This uses the redact function from the redaction chapter. Truncation limits the damage if a message is very long, but it is not a substitute for redaction, because a key can sit in the first 300 characters.
Tracebacks need the same care. Some frameworks and tools such as Sentry can attach local variables to a stack trace, which includes any variable named api_key or headers. Turn off local-variable capture in production, or configure the tool's scrubbing rules for the names you use.
Control 6: Add secret patterns to the content redactor
Keys can still arrive inside prompts and responses. Extend the content redactor with the formats your providers use. Prefer patterns that match a distinctive prefix, so they do not hide ordinary words.
import re
SECRET_PATTERNS = [
re.compile(r"\b(?:sk|key|token)[-_][A-Za-z0-9_-]{16,}\b"),
re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
re.compile(r"\bBearer\s+[A-Za-z0-9._~+/=-]{16,}"),
re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
]
def redact_secrets(text: str) -> str:
for pattern in SECRET_PATTERNS:
text = pattern.sub("[SECRET]", text)
return textThe patterns are examples. AKIA followed by 16 characters is the shape of an AWS access key ID, and the Bearer pattern catches tokens in pasted headers. Look up the exact formats for the providers you use and add them.
Control 7: Respond when a key does leak
Plan for the failure. If a credential reaches a log, the key is compromised, even if the log system is private.
- Revoke or rotate the key first. Do this before cleaning up the logs.
- Find where it was written and how far it spread: the log store, backups, exported files, alert messages.
- Purge or expire the affected entries where you can.
- Add the leak to your redaction tests so it cannot return.
Short-lived credentials reduce the cost of this step. Keys that expire in hours, or per-service keys with narrow scope and a spending limit, make a leak far less damaging than a single long-lived key shared by every service.
Test that credentials stay out
A leak fixed by hand will come back unless a test guards it. Test both the masking type and the whole call path with a fake key.
import io
import json
import logging
def test_secret_is_masked():
s = Secret("sk-abcdefghijklmnop1234")
assert "sk-abcdefghijklmnop1234" not in repr(s)
assert "sk-abcdefghijklmnop1234" not in str(s)
assert "sk-abcdefghijklmnop1234" not in f"{s}"
def test_error_log_has_no_key():
stream = io.StringIO()
handler = logging.StreamHandler(stream)
log = logging.getLogger("leaktest")
log.addHandler(handler)
log.setLevel(logging.INFO)
fake_key = "sk-abcdefghijklmnop1234"
try:
raise ConnectionError(f"failed for https://api.example.com/?key={fake_key}")
except Exception as exc:
log.info(json.dumps(safe_error(exc)))
assert fake_key not in stream.getvalue()Use a recognizable fake key so any appearance in output is easy to find. A broader version of this test runs the real call wrapper against a stub client that fails with the key in its message, then searches the captured log output for the key.
Common mistakes
- Logging the client object or a settings object "for debugging" and forgetting that it holds the key.
- Setting the root logger to
DEBUGin production and exposing library request logs. - Using a denylist of sensitive headers instead of an allowlist of safe ones.
- Redacting content but not exception messages.
- Cleaning logs after a leak without rotating the key.
- Using one long-lived key for every environment, so a leak from a test system exposes production.
Exercise
Your service logs str(exc) when an LLM call fails. A provider error message includes the request URL, which contains ?key=sk-.... Name two changes that stop the key from reaching the log, and say why redaction alone is a weaker choice than the first one.
Show answer
First, log only the exception type and a short controlled message (or send the key in a header and keep it out of URLs), so the key text is never part of what gets logged. Second, pass any message you do log through the secret redactor and truncate it. Redaction alone is weaker because it depends on a pattern matching the key's shape. A key with an unexpected format passes through, while a value that was never logged cannot leak.
Exercise
A teammate sets the root logger to DEBUG to investigate a timeout, and the Authorization header appears in the logs. Which control prevents this, and how does it work?
Show answer
Control 4: set explicit levels (such as WARNING) on the HTTP and SDK loggers, for example urllib3, httpx, and the provider SDK. Each library logger then ignores the root level, so raising the root to DEBUG does not switch on their request logging. Apply this after any framework code that resets logging configuration.