Sub topic 3
A Logging Policy: Metadata by Default, Content by Exception
What this chapter assumes
You can call an LLM API from Python and know how application logging and log levels work. You can read a basic regular expression. Earlier chapters covered where sensitive data hides in LLM traffic. This chapter turns that knowledge into a written rule that decides, for every field, whether it is logged. Later chapters cover the mechanics of redaction, truncation, and retention.
Why write a policy before writing code
Without a policy, each developer decides in the moment what to log. One adds logger.debug(prompt) while chasing a bug. Another logs the whole request object, headers included. Months later the logs hold customer emails, pasted contracts, and bearer tokens. Nobody chose that outcome. It built up through many small, reasonable-looking decisions.
A logging policy replaces those decisions with one rule that the code enforces. The rule used in this tutorial is:
- Log metadata on every call. Metadata describes the call and says nothing about what was written in it.
- Log content (the prompt text and the response text) only by exception. The exception must be deliberate, limited in scope, and limited in time.
- Never log credentials, under any setting.
The reason for this split is cost against value. Metadata answers most operational questions: how many calls failed, which model was slow, what a day of traffic cost. It carries little privacy risk. Content is only occasionally needed, for example to debug a bad answer. It carries most of the risk, because it holds whatever users and documents put into it.
The three tiers
Sort every field you might log into one of three tiers.
| Tier | Meaning | Example fields | Rule |
|---|---|---|---|
| Always | Describes the call, not its text | `request_id`, `model`, `status`, `latency_ms`, `prompt_chars`, `response_chars`, `prompt_sha256`, `error_type` | Logged on every call |
| Gated | Contains user or document text | `prompt`, `response` | Logged only when an exception is active, and only after redaction and truncation |
| Never | Grants access or identifies a person directly | `Authorization` header, API keys, session cookies, raw request headers | Dropped in every mode |
A few of these placements need explanation.
- Character counts and token counts are metadata. They reveal size, not content. Be aware that very unusual sizes can still hint at content, such as a document of exactly known length. For most systems this risk is acceptable.
- A prompt hash is metadata, with a caveat. A SHA-256 hash lets you group identical prompts and spot repeated requests without storing text. A hash of a short or guessable prompt, such as
"yes"or a template with one filled-in name, can be reversed by trying candidates. Treat hashes of short inputs as weaker than they look. A later chapter covers keyed hashing. - Error messages sit between tiers. The exception type (
TimeoutError) is safe. The exception message sometimes echoes the request body, so log the type and a status code by default, and keep the message in the gated tier. - User identifiers need a decision. A raw user ID or email in every record turns your logs into a personal-data store. Prefer a pseudonymous ID, or leave it out until you need it.
How the decision flows
For each field in a log record, the code asks three questions in order.
Note the last branch where a field is on no list: it is dropped. This makes the policy an allowlist. A field is logged only because someone named it. A denylist works the other way, and it fails whenever a new field appears that nobody thought to block. SDK upgrades, middleware, and new teammates add fields all the time, so the allowlist is the safer default.
The policy as code
Keep the policy in one place, as data, so reviewers can read it in a single glance. The function below enforces the three tiers on a record before it reaches the logger.
import json
ALWAYS = {
"event", "request_id", "model", "status", "latency_ms",
"prompt_chars", "response_chars", "prompt_sha256",
"error_type", "temperature", "max_tokens",
}
GATED = {"prompt", "response", "error_message"}
NEVER = {"api_key", "authorization", "headers", "cookie"}
def apply_policy(record: dict, content_allowed: bool) -> dict:
out = {}
dropped = []
for key, value in record.items():
if key in NEVER:
dropped.append(key)
elif key in ALWAYS:
out[key] = value
elif key in GATED and content_allowed:
out[key] = value
else:
dropped.append(key)
if dropped:
out["dropped_fields"] = sorted(dropped)
return out
record = {
"event": "llm_call",
"request_id": "r1",
"model": "m-1",
"status": "ok",
"latency_ms": 820,
"prompt": "hello",
"authorization": "Bearer abc",
"temperature": 0.2,
}
print(json.dumps(apply_policy(record, content_allowed=False)))
print(json.dumps(apply_policy(record, content_allowed=True)))The output is:
{"event": "llm_call", "request_id": "r1", "model": "m-1", "status": "ok", "latency_ms": 820, "temperature": 0.2, "dropped_fields": ["authorization", "prompt"]}
{"event": "llm_call", "request_id": "r1", "model": "m-1", "status": "ok", "latency_ms": 820, "prompt": "hello", "temperature": 0.2, "dropped_fields": ["authorization"]}Three details matter here.
NEVERis checked first, so no configuration can put a credential into a log by also listing it elsewhere.dropped_fieldsrecords the names of dropped fields, never their values. When someone wonders why a field is missing, the log answers the question. This also reveals when a new, unexpected field starts appearing.- The policy gate does not redact. When
content_allowedis true, the content fields must already have been redacted and truncated by the time they reach this function. The wrapper from the topic's earlier code does that withredact(prompt)[:2000].
Controlling the exception
The gate that sets content_allowed is where most real leaks happen, because gates tend to be switched on and forgotten. Give the gate three properties.
- It fails closed. If the setting is missing, malformed, or unreadable, content logging stays off.
- It expires. The setting holds a deadline, not a boolean. Past the deadline the gate turns itself off, and nobody has to remember.
- It is narrow. Where you can, scope it to one request ID, one test account, or one route, not the whole service.
import os
import time
def content_logging_enabled(now: float | None = None) -> bool:
until = os.environ.get("LLM_LOG_CONTENT_UNTIL")
if not until:
return False
try:
return (now if now is not None else time.time()) < float(until)
except ValueError:
return FalseSetting LLM_LOG_CONTENT_UNTIL to an epoch timestamp one hour ahead enables content logging for an hour. An empty value, a typo such as tomorrow, or a timestamp in the past all produce False.
A process-wide environment variable is the simplest gate, but it is also the broadest. In a multi-user service, prefer a per-request flag that only an authorized operator or a test harness can set. Do not let end users set it through request parameters, or a user could cause their own data, or someone else's, to be written to logs.
Rules for the exception
Write down the conditions under which the exception is allowed. A short list is enough.
- Who may enable it, and who approves.
- The reason, recorded with the change (a ticket number works).
- The maximum duration, typically hours, not days.
- Where the content goes. Debug content belongs in a separate log destination with tighter access and shorter retention than the metadata logs. Mixing them means everyone who reads latency charts can also read prompts.
- Who reviews and deletes the captured content afterward.
Access control and retention are covered in a later chapter. The policy only has to say that the separate destination exists.
Edge cases
- Local development. Developers often want full prompts. Allow this when the logger writes to the developer's terminal and nowhere else, and make sure the same setting cannot reach production configuration. Default to the production behavior and make local content logging an explicit opt-in.
- Error paths. Failures are when people most want content, and when code is most likely to log carelessly. Exception handlers that call
logger.exception(...)can include the request body through the exception message or traceback locals. Route error records through the sameapply_policyfunction as success records. - Third-party libraries. An HTTP client set to debug level can print full request bodies and headers on its own, bypassing your wrapper. Check the log level of the HTTP and SDK loggers separately, and keep them at warning or above in production.
- Evaluation and training data. If you need prompt and response pairs for evaluation, that is a data collection decision with its own consent and retention rules. Do not satisfy it by quietly leaving content logging on.
- Observability vendors. Auto-instrumentation tools can capture prompts and responses as span attributes. Those attributes leave your system. Apply the same allowlist to them, or turn content capture off in the tool's settings.
Common errors
- Using a denylist, then adding a new field that the denylist does not mention.
- Logging the full request object "just in case" at debug level, and shipping with debug level on.
- Treating a boolean
LOG_CONTENT=trueas a permanent switch. It outlives the bug it was meant to find. - Logging content to the same stream as metadata, so the gated data inherits broad access and long retention.
- Dropping fields silently, then losing hours debugging "missing" data. Log the dropped field names.
- Assuming a hash makes a short or guessable prompt anonymous.
Exercise
A teammate adds a field user_email to the log record in a service that uses the apply_policy function above, and does not edit ALWAYS, GATED, or NEVER. What happens to that field when content logging is off, and again when it is on? What should the teammate do if they believe the email is needed in logs?
Show answer
In both modes the field is dropped, because it appears in none of the three lists and the function only logs fields that an allowlist names. The name user_email shows up in dropped_fields, so the omission is visible. If the email is truly needed, the teammate should first ask whether a pseudonymous user ID would serve, since that avoids storing personal data in every record. If the email itself is required, they must place it in a tier through a reviewed change. It belongs in the gated tier with redaction, not in the always tier.