Sub topic 13
Opt-in, time-limited content logging for debugging
Metadata-first logging tells you that a call was slow or failed. It rarely tells you why the model gave a bad answer. For that you sometimes need the actual prompt and response. This chapter covers how to allow content logging for a narrow target and a short time, and how to make sure it switches itself off.
This chapter assumes you have read the earlier chapters on the logging policy and redaction. You should be comfortable with Python, the standard logging module, and basic regular expressions. The code reuses redact and call_logged from earlier in the tutorial.
Why content logging needs a gate
The logging policy says metadata by default and content by exception. An exception needs rules, or it turns into the default. Three failure modes show up often:
- Someone sets
log_content=Trueduring an incident and never reverts it. - Content logging is turned on for every user when only one user's requests are failing.
- Nobody knows who enabled it, why, or when it should end.
A gate fixes these by making content logging opt-in, narrow, and temporary. Each enablement carries a scope, an expiry time, a reason, and an owner.
What a gate contains
A content-logging grant is a small record with these fields:
| Field | Purpose |
|---|---|
| `scope` | What the grant matches, such as one user hash, one feature name, or one request ID |
| `expires_at` | A UTC timestamp after which the grant is ignored |
| `reason` | A short note, such as a ticket number |
| `granted_by` | The person who approved it |
| `max_records` | An optional cap on how many records the grant may produce |
The expiry is checked at the moment of each call, against the clock. It is not enforced by someone remembering to turn the flag off. If the process restarts, or the cleanup job fails, an expired grant still does nothing.
The decision flow
On every call, the wrapper asks whether a live grant matches. If not, it logs metadata only.
Every path ends with the metadata record. Content logging adds to the normal record. It never replaces it.
Implementing a grant store
This version keeps grants in memory so it is easy to run. A real service would load them from a config store or database so that one operator action reaches every instance.
import time
from dataclasses import dataclass, field
@dataclass
class Grant:
scope: str
expires_at: float # Unix timestamp, UTC
reason: str
granted_by: str
max_records: int = 50
used: int = field(default=0)
class GrantStore:
def __init__(self, clock=time.time):
self._grants = {}
self._clock = clock
def add(self, grant: Grant) -> None:
self._grants[grant.scope] = grant
def revoke(self, scope: str) -> None:
self._grants.pop(scope, None)
def check(self, *scopes: str):
"""Return a live grant for any scope, consuming one record, or None."""
now = self._clock()
for scope in scopes:
grant = self._grants.get(scope)
if grant is None:
continue
if now >= grant.expires_at or grant.used >= grant.max_records:
self._grants.pop(scope, None)
continue
grant.used += 1
return grant
return None
if __name__ == "__main__":
store = GrantStore()
store.add(Grant("feature:summarize", time.time() + 600, "TICKET-1234", "ana", max_records=2))
for _ in range(3):
g = store.check("user:abc123", "feature:summarize")
print("granted" if g else "metadata only")The loop prints granted, granted, then metadata only, because the cap of two records is used up. The clock is injected as a parameter. That lets tests move time forward without sleeping.
Note that check deletes expired grants as a side effect. This keeps the store small, but correctness never depends on it. The expiry comparison runs on every call.
Wiring the gate into the call wrapper
Earlier, call_logged took a log_content boolean. Replace the boolean with a grant lookup. The caller no longer decides. The store does.
import hashlib
import json
import logging
import re
import time
import uuid
logger = logging.getLogger("llm")
content_logger = logging.getLogger("llm.content")
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
API_KEY = re.compile(r"\b(?:sk|key|token)[-_][A-Za-z0-9_-]{16,}\b")
def redact(text: str) -> str:
text = EMAIL.sub("[EMAIL]", text)
return API_KEY.sub("[SECRET]", text)
def call_gated(client_call, store, model: str, prompt: str, user_hash: str, feature: str) -> str:
request_id = str(uuid.uuid4())
record = {
"event": "llm_call",
"request_id": request_id,
"model": model,
"prompt_chars": len(prompt),
"prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
}
grant = store.check(f"user:{user_hash}", f"feature:{feature}", f"request:{request_id}")
if grant:
record["content_grant"] = {"scope": grant.scope, "reason": grant.reason, "granted_by": grant.granted_by}
start = time.perf_counter()
response = None
try:
response = client_call(model=model, prompt=prompt)
record["status"] = "ok"
record["response_chars"] = len(response)
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))
if grant:
content_logger.info(json.dumps({
"event": "llm_content",
"request_id": request_id,
"prompt": redact(prompt)[:2000],
"response": redact(response or "")[:2000],
}))Several choices here are deliberate:
- Content goes to a separate logger.
llm.contentcan be routed to a different sink with stricter access and shorter retention, without touching the metadata stream. - The metadata record names the grant. Anyone reading the logs can see that content was captured, and under whose approval. This gives you an audit trail.
- The two records share
request_id. You can join them when you have permission to read both. - Content still passes through
redactand truncation. A grant widens what you log. It does not turn off the earlier protections. - The call can fail. If the API raises,
responsestaysNone, and the prompt is still logged. That is often the case you want most.
Routing the content logger
Python's logging can send the llm.content logger to its own file with its own handler. Set propagate to False so records do not also land in the general log.
import logging
import logging.handlers
def configure_content_sink(path: str) -> None:
handler = logging.handlers.RotatingFileHandler(path, maxBytes=5_000_000, backupCount=2)
handler.setFormatter(logging.Formatter("%(message)s"))
content = logging.getLogger("llm.content")
content.setLevel(logging.INFO)
content.propagate = False
content.addHandler(handler)Without propagate = False, the child logger passes records up to llm, and your protected content ends up in the ordinary stream. This is an easy mistake to make, and a unit test can catch it.
The rotating handler's backupCount caps how much content can accumulate on disk. It is a size limit, not a retention policy, so a file-age cleanup job or storage lifecycle rule should still delete old files. The next chapter covers retention.
Choosing scopes
Narrow scopes limit the privacy cost of debugging. A rough order from narrowest to widest:
- One request ID. Good when a user reports a specific bad answer and you can reproduce it.
- One hashed user. Good for a bug that follows a person, such as an odd account setting.
- One feature or prompt template. Good when a template change caused a regression.
- A percentage of all traffic. Use only when nothing narrower works, and keep the percentage and the window small.
Use the hashed user identifier from the earlier hashing chapter, not a raw email address, as the scope string. The grant record itself is then not a place where personal data leaks.
Setting durations
Choose the shortest window that lets you collect enough examples. For a reproducible bug, minutes are enough. For an intermittent one, a few hours may be needed. Set a hard maximum in code, so that nobody can create a grant that lasts a month:
MAX_GRANT_SECONDS = 24 * 3600
def make_grant(scope, seconds, reason, granted_by, max_records=50):
if not reason.strip():
raise ValueError("a reason is required")
seconds = min(seconds, MAX_GRANT_SECONDS)
return Grant(scope, time.time() + seconds, reason, granted_by, max_records)Requiring a reason makes people write down why they are collecting sensitive text. Capping the duration means that renewing a grant is an explicit second decision.
Common errors
- Expiry checked only at grant time. If the code only checks once when the grant is created, long-lived processes keep logging. Check on every call.
- Content logger propagates to the root logger. The restricted sink is bypassed.
- A grant on a broad scope with no cap. Always set
max_records. - Skipping redaction because it is "just debugging". Debug logs are stored, shipped, and searched like any other logs.
- Forgetting streamed calls. A gated stream should reuse the same check, then call the stream wrapper's log function only when a grant exists.
- Clock differences between servers. Use UTC timestamps, and allow for a few seconds of skew. An expiry that is a few seconds late is a smaller problem than one that never fires.
Testing the gate
Use the injected clock to test expiry without waiting.
def test_grant_expires_and_caps():
now = [1000.0]
store = GrantStore(clock=lambda: now[0])
store.add(Grant("feature:x", 1060.0, "TICKET-1", "ana", max_records=1))
assert store.check("feature:x") is not None # first use
assert store.check("feature:x") is None # cap reached
store.add(Grant("feature:x", 1060.0, "TICKET-1", "ana", max_records=5))
now[0] = 1061.0
assert store.check("feature:x") is None # expiredAlso test the negative path. With no grant, the content logger must receive nothing.
Exercise
A teammate sets log_content=True in a config file to debug one customer's failures and plans to turn it off "next week". Name three problems with this approach and describe the gated design that fixes them.
Show answer
Problems: (1) it applies to all traffic, not just that customer, so it logs far more personal data than needed; (2) it has no automatic end, so it depends on someone remembering; (3) it leaves no record of who enabled it or why. The gated design uses a grant scoped to the customer's hashed user ID, with an expires_at checked on every call, a max_records cap, and reason and granted_by fields written into the metadata record. Content goes to a separate restricted logger, still redacted and truncated.
Exercise
In call_gated, why is the prompt logged even when the API call raises an exception, and why does the code write redact(response or "")?
Show answer
The content record is written in the finally block, so it runs whether the call succeeds or fails, and failed calls are often the ones you need to inspect. If the call raised, response is still None, and redact(None) would fail on the regex substitution, so response or "" supplies an empty string instead.