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. Credentials are the most damaging thing a log can leak. A leaked API key lets anyone run up your bill or read data tied to your account, and it stays valid until someone rotates it.
Where credentials leak
Credentials rarely end up in logs on purpose. They arrive through a few common paths:
- Request headers. An
Authorization: Bearer ...header or anx-api-keyheader is logged when you dump a full HTTP request. - Exception messages. Some client libraries include the URL, headers, or configuration in an error string.
- Debug logging in HTTP libraries. Turning on
DEBUGfor a client or forurllib3can print every header. - Prompts. Users paste keys into chat, and your own code may build prompts from config files that contain secrets.
- Configuration dumps. Logging
os.environor a settings object at startup writes every secret at once.
Rule 1: log fields you choose, not objects you have
The safest habit is an allowlist. Build each log record from named fields you picked, as the call_logged wrapper in this tutorial does. Never pass a whole request, response, headers dictionary, or settings object to the logger.
import json
import logging
logger = logging.getLogger("llm")
# Risky: writes every header, including Authorization
def log_request_bad(headers: dict) -> None:
logger.info(json.dumps(headers))
# Safer: copies only fields you have approved
SAFE_HEADERS = {"content-type", "x-request-id"}
def log_request_good(headers: dict) -> None:
safe = {k: v for k, v in headers.items() if k.lower() in SAFE_HEADERS}
logger.info(json.dumps(safe))A blocklist ("remove Authorization") fails when a new header such as x-goog-api-key appears. An allowlist fails safe, because unknown fields are dropped.
Rule 2: keep secrets out of your code and prompts
Read keys from environment variables or a secrets manager, and pass them directly to the client. Do not put them in prompt templates or in objects you might log.
import os
api_key = os.environ["LLM_API_KEY"] # raises KeyError if missingNever print the key to confirm it loaded. If you need to confirm which key is in use, log a short fingerprint instead, such as the last four characters.
def key_hint(key: str) -> str:
return "..." + key[-4:] if len(key) >= 8 else "[short]"Rule 3: filter at the logging layer
Individual call sites make mistakes. A logging filter is a second line of defense that scrubs every record, including those from third-party libraries.
import logging
import re
SECRET = re.compile(r"\b(?:sk|key|token)[-_][A-Za-z0-9_-]{16,}\b")
BEARER = re.compile(r"(?i)bearer\s+[A-Za-z0-9._~+/=-]+")
class SecretFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
message = record.getMessage()
message = SECRET.sub("[SECRET]", message)
message = BEARER.sub("Bearer [SECRET]", message)
record.msg = message
record.args = ()
return True
handler = logging.StreamHandler()
handler.addFilter(SecretFilter())
logging.getLogger().addHandler(handler)Attach the filter to the handler, not to a single logger. Filters on a logger do not run for records that propagate up from child loggers, but filters on a handler run for every record that handler emits.
Rule 4: quiet third-party loggers
HTTP libraries can log headers at DEBUG level. Pin them to WARNING in production.
import logging
for name in ("urllib3", "httpx", "httpcore", "openai"):
logging.getLogger(name).setLevel(logging.WARNING)If a key does leak
Assume it is compromised. Revoke and rotate it first. Then find and purge the log lines, and check provider usage records for activity you did not make. Deleting the log line without rotating the key does not help, because copies may exist in backups and log shippers.
Exercise
Why is an allowlist of logged header names safer than a blocklist that removes Authorization?
Show answer
A blocklist only removes headers you thought of, so a new credential header such as x-goog-api-key would be logged. An allowlist logs only approved headers, so unknown headers are dropped by default.
Exercise
A teammate logs a key to the console by mistake, and you delete the log line. What must you still do?
Show answer
Revoke and rotate the key, because it may have been copied to backups or log shippers. Then check provider usage for activity you did not make.