Sub topic 11
Truncating and Sampling Logged Content
This chapter assumes you can call an LLM API, use Python's logging module, and read basic regular expressions. It also assumes you have read the earlier chapters on the logging policy and on redaction. Truncation and sampling are the two ways to log less content. Less logged content means less data that can leak, lower storage cost, and smaller logs to search.
Why limit content
Prompts can be very long. A retrieval-augmented prompt may include whole documents, and a response may run to thousands of tokens. Logging all of it has three costs:
- More sensitive text is stored, so a leak is worse.
- Log lines grow large. Some log pipelines reject or silently cut lines above a size limit.
- Storage and search costs rise with volume.
Truncation limits how much of each record you keep. Sampling limits how many records you keep content for. You can use both together.
Truncation
Truncation means keeping only the first part of a string. The wrapper from earlier chapters does this with [:2000].
The order of operations matters. Redact first, then truncate. If you truncate first, the cut can land in the middle of an email address or key. The redaction pattern then no longer matches, and the partial secret stays in the log.
def safe_excerpt(text: str, limit: int = 2000) -> str:
redacted = redact(text)
if len(redacted) <= limit:
return redacted
return redacted[:limit] + f"...[truncated {len(redacted) - limit} chars]"Note that this function assumes redact from the redaction chapter is defined. The marker at the end tells a reader that text was cut, and by how much. Without it, a truncated record looks like a complete one.
A cut can still leave a partial placeholder such as [EMA. That is harmless, but it can confuse people reading the log.
Choose the limit from your debugging needs, not from the model's context size. A few hundred characters is often enough to identify which prompt template was used. If you need the end of a response, keep both the head and the tail.
Sampling
Sampling means logging content for only a fraction of calls. Metadata is still logged for every call, so cost and latency data stay complete.
The simplest form is random sampling. A better form is deterministic sampling based on the request ID. Because the decision depends only on the ID, the same request always gets the same answer. This keeps prompt and response consistent, so you never log one without the other.
import hashlib
def should_sample(request_id: str, rate: float) -> bool:
digest = hashlib.sha256(request_id.encode("utf-8")).digest()
bucket = int.from_bytes(digest[:4], "big") / 2**32
return bucket < rate
print(should_sample("req-123", 0.05))At a rate of 0.05, about 5 percent of requests pass. Use this result as the log_content flag in call_logged.
You can also always keep content for errors. Failed calls are rare and are the ones you most want to inspect. Redaction and truncation still apply to them.
log_content = record["status"] == "error" or should_sample(record["request_id"], 0.02)How the pieces combine
The diagram shows the order of decisions for each call.
Common errors
| Error | Result | Fix |
|---|---|---|
| Truncating before redacting | Partial secrets escape the patterns | Redact first |
| No truncation marker | Cut text looks complete | Append a marker with the cut length |
| Random sampling per field | Prompt logged without its response | Decide once per request |
| Sampling metadata too | Cost and latency data become estimates | Sample content only |
Exercise
A teammate truncates the prompt to 2000 characters and then calls redact on the result. Why can this leak a secret, and what is the fix?
Show answer
A key that straddles character 2000 is cut in half. The remaining fragment may be shorter than the pattern requires, such as 16 or more characters after the prefix, so redact does not match it and the fragment is logged. Redact the full text first, then truncate.
Exercise
Why is should_sample based on a hash of the request ID better than random.random() < rate called separately for the prompt and the response?
Show answer
The hash gives one fixed decision per request, so the prompt and response are either both logged or both skipped. Two separate random calls could log one without the other. A hash decision is also reproducible, so you can recompute it later to see whether a given request was sampled.