Sub topic 3
A logging policy: metadata by default, content by exception
This chapter assumes you can call an LLM API from Python, know application log levels, and can read basic regular expressions. It covers the policy that decides what your logging code records. The later chapters build the mechanisms.
Why you need a written policy
Without a policy, each developer decides what to log. One person logs the full prompt "just for now". Another logs the raw response. A third logs the request headers, which include the API key. Months later, the logs hold customer emails, pasted contracts, and credentials.
A logging policy is a short written rule set that says which fields are always logged, which are logged only under conditions, and which are never logged. Code then enforces it in one place.
The three tiers
Sort every field into one of three tiers.
| Tier | Rule | Examples |
|---|---|---|
| Always | Safe to log on every call | request ID, model name, status, latency, prompt and response size, error type, prompt hash |
| By exception | Logged only when a gate is open, and always redacted and truncated | prompt text, response text |
| Never | Not logged under any setting | API keys, authorization headers, raw request headers, unredacted content |
Metadata tells you how the system behaves: how often calls fail, how slow they are, and what they cost. Most operational questions need nothing more. Content tells you what was said, and it carries most of the privacy risk. Keeping the two apart lets you answer the first kind of question without storing the second kind of data.
The prompt hash
A hash of the prompt gives you something useful without storing the text. A SHA-256 hash is a fixed-length fingerprint of the input. Identical prompts give identical hashes, so you can find repeated requests, group failures, and check whether a prompt template changed. Nobody can read the prompt back from the hash.
One caution: short or guessable prompts can be confirmed by hashing a guess. Treat the hash as lower risk, not as risk-free.
The policy in code
The wrapper below enforces the policy. It uses redact from the previous chapter's pattern-based redactor.
import hashlib
import json
import logging
import time
import uuid
logger = logging.getLogger("llm")
def call_logged(client_call, model: str, prompt: str, log_content: bool = False) -> str:
record = {
"event": "llm_call",
"request_id": str(uuid.uuid4()),
"model": model,
"prompt_chars": len(prompt),
"prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
}
start = time.perf_counter()
try:
response = client_call(model=model, prompt=prompt)
record["status"] = "ok"
record["response_chars"] = len(response)
if log_content:
record["prompt"] = redact(prompt)[:2000]
record["response"] = redact(response)[:2000]
return response
except Exception as exc:
record["status"] = "error"
record["error_type"] = type(exc).__name__
raise
finally:
record["latency_ms"] = round((time.perf_counter() - start) * 1000)
logger.info(json.dumps(record))Each part maps to the policy:
- The
recordfields set before the call are the "always" tier. log_contentdefaults toFalse, so content is off unless someone turns it on.- When it is on,
redactruns before truncation to 2000 characters. Redacting first matters, because truncating first could cut a secret in half and let the remaining fragment slip past a pattern. - The wrapper never sees headers or the API key. It logs
type(exc).__name__instead ofstr(exc), because exception messages sometimes echo request details. - The
finallyblock logs once, whether the call succeeded or failed.
Who opens the gate
The log_content flag is a gate, and a gate needs rules. Decide these in the policy, not in the code review:
- Who may enable it, and for which service or user.
- Why: a named incident or bug, not general curiosity.
- For how long. Content logging should expire on its own.
- Where the content goes, and who can read it.
A later chapter covers opt-in, time-limited logging and access control in detail. For now, the point is that the default is off and turning it on is a deliberate act.
Common mistakes
- Adding content logging at
DEBUGlevel and assuming production ignores it. Log levels get changed during incidents. - Logging the whole request object, which may carry headers or credentials.
- Having several places that write logs, so the policy is enforced in some and not others. Route all LLM calls through one wrapper.
Exercise
A teammate wants to log the full response text on every call so that support can search it later. Using the three-tier policy, what do you answer, and what could they log instead?
Show answer
Response text belongs in the "by exception" tier, so it should not be logged on every call. Instead, always log metadata such as the request ID, response size, status, and a hash. Support can then find a specific call by request ID. If the team needs the text for a specific bug, open the content gate for a limited time, with redaction and truncation, and with restricted access.
Exercise
In call_logged, why is redact applied before the [:2000] slice and not after?
Show answer
Slicing first could cut a secret or email address partway through. The shortened fragment might no longer match the redaction pattern and would be logged as plain text. Redacting the full string first removes the whole match, and truncation then only limits the size.