Sub topic 11
Truncating and Sampling Logged Content
Prerequisites
This chapter assumes you have read the earlier chapters on the logging policy, structured logs, and redaction. You should be comfortable with Python, JSON log records, and basic regular expressions. The code reuses the redact function from the redaction chapter. A copy is included so the examples run on their own.
Why limit content even after redaction
Redaction removes the sensitive strings you know how to match. Truncation and sampling cover the ones you don't.
- Truncation caps how much text from one call can enter a log record. A leak that gets past redaction exposes at most a few thousand characters, not a whole 100,000-character document.
- Sampling caps how many calls have their content logged at all. If only 1 in 100 calls stores text, a pattern gap affects about 1% of your traffic.
Both also reduce storage cost and keep records small enough for your log pipeline. Many log systems reject or split lines above a size limit, often between 16 KB and 256 KB. A long prompt can push a record over that limit, and then the metadata you wanted is lost along with the content.
Neither technique replaces the policy of logging metadata by default. They are limits on the exceptions: the content you have decided to log.
Truncation
Redact first, then truncate
The order matters. Suppose a response contains sk-abcdefghijklmnop1234 and your cut falls in the middle of it. If you truncate first, the log holds sk-abcdefghij. That fragment is shorter than the 16 characters after the prefix that the API_KEY pattern requires, so the pattern no longer matches. The redactor misses it, and part of the secret reaches the log.
So the rule is: redact the full text, then truncate the redacted result. Redacting a long string costs more CPU, but you only do it for calls that will actually be logged. Sampling, described below, decides that first, so the cost stays low.
Head and tail
A plain text[:2000] keeps the start and drops the end. For prompts this is often fine. For model responses the end can matter, because it shows whether the output was cut off, ended with a refusal, or finished the JSON. A common choice is to keep a head and a short tail, and put a marker between them that says how much was removed.
import hashlib
import re
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)
text = API_KEY.sub("[SECRET]", text)
return text
def truncate(text: str, max_chars: int = 2000, tail_chars: int = 200) -> str:
if tail_chars >= max_chars:
raise ValueError("tail_chars must be smaller than max_chars")
if len(text) <= max_chars:
return text
head_chars = max_chars - tail_chars
omitted = len(text) - max_chars
return f"{text[:head_chars]}...[{omitted} chars omitted]...{text[-tail_chars:]}"
print(truncate("a" * 50, max_chars=20, tail_chars=5))
# aaaaaaaaaaaaaaa...[30 chars omitted]...aaaaaThe kept text is exactly max_chars characters, and the marker reports how many characters were dropped. That number is useful when you read the log later, because it tells you whether the record shows most of the text or a small part of it.
Edge cases in truncation
| Situation | Problem | What to do |
|---|---|---|
| Limit counted in characters, but the log system limits bytes | A 2,000-character string of non-Latin text can take 6,000 bytes in UTF-8 | Size the limit for the worst case, or truncate by encoded bytes and decode with `errors="ignore"` |
| Cut falls inside a placeholder | A cut `[SECRET` is harmless but confusing | Accept it, or cut before redaction only when you know no pattern spans the cut (usually you don't) |
| Cut falls inside a JSON escape | Only matters if you truncate the serialized record | Truncate the field values, then serialize with `json.dumps` |
| Very large input | `redact` runs a regex over megabytes | Apply a hard pre-limit (for example 50,000 characters) before redaction, and log the original length separately |
| Empty or `None` response | `len(None)` raises a `TypeError` | Convert with `text or ""` before you call `truncate` |
The pre-limit in the fifth row creates the same cut-in-the-middle risk described above, but at a much larger scale. A secret that straddles the 50,000-character boundary is rare. If you want to remove even that risk, cut at a whitespace boundary or overlap the window by a few hundred characters.
Always truncate field values, never the finished JSON line. Cutting a JSON string at a fixed length produces invalid JSON that parsers reject, and log tools may drop the whole line.
Sampling
Random versus deterministic sampling
The simplest approach is random.random() < rate. It works, but each call decides independently. If one request makes several LLM calls (a retrieval step, a rewrite, a final answer), a random sampler might log the content of the second call and skip the first and third. When you debug, you want all of the calls from one request, or none.
A deterministic sampler hashes the request ID and turns the hash into a number between 0 and 1. The same ID always gives the same number, so every call in that request gets the same decision. It also gives the same decision across processes and servers, with no shared state.
def should_sample(request_id: str, rate: float) -> bool:
if rate >= 1:
return True
if rate <= 0:
return False
digest = hashlib.sha256(request_id.encode("utf-8")).digest()
bucket = int.from_bytes(digest[:8], "big") / 2**64
return bucket < rateThe first 8 bytes of a SHA-256 digest are close to uniformly distributed, so about rate of all IDs fall below the threshold. This works as long as request IDs are unique per request. If you reuse an ID for a whole user session, the sampler picks whole sessions, which may or may not be what you want.
Always keep the interesting calls
A flat 1% rate means you probably have no content for the one failure you need to debug. A common refinement is to treat the decision as two parts: a base sample rate for normal calls, and a higher rate (or always) for errors and slow calls. Error calls have no response text, but the redacted prompt is often the key evidence.
This increases the volume of logged content, so it must stay inside the gate set by your policy. Sampling never turns content logging on. It only reduces how much of the content you already allowed.
def content_fields(
request_id: str,
prompt: str,
response: str | None,
status: str,
enabled: bool,
sample_rate: float = 0.01,
error_rate: float = 1.0,
) -> dict:
if not enabled:
return {}
rate = sample_rate if status == "ok" else error_rate
if not should_sample(request_id, rate):
return {}
fields = {"prompt": truncate(redact(prompt)), "content_sampled": True}
if response is not None:
fields["response"] = truncate(redact(response))
return fields
record = {"event": "llm_call", "request_id": "req-123", "status": "ok"}
record.update(
content_fields("req-123", "Mail [email protected]", "Sure.", "ok", enabled=True, sample_rate=1.0)
)
print(record)
# {'event': 'llm_call', 'request_id': 'req-123', 'status': 'ok', 'prompt': 'Mail [EMAIL]', 'content_sampled': True, 'response': 'Sure.'}The function returns an empty dict when content is off or the call is not sampled, so the metadata record is unchanged. Adding a content_sampled flag helps later analysis. Without it, a missing prompt field is ambiguous: it could mean the call was not sampled, or that the field was lost.
Sampling has statistical consequences
Do not compute metrics from sampled records. Token counts, latency, and status belong in the metadata record, which you log for every call. Content is the only part you sample. If you sample whole records, your error rate and cost totals become estimates, and you have to scale them by the rate.
Sampling at 1% also hides rare problems. If a prompt-format bug affects 0.1% of calls, a 1% sample shows it in about one call in a thousand sampled records. To find a specific problem, raise the rate temporarily. The next chapters cover how to do that with time-limited content logging.
The full order of operations
The order of the steps is part of the design. Each step shrinks the exposure that the next step has to handle.
Because the sampling check comes before redaction, the expensive regex work runs on only a small share of calls. Because truncation comes after redaction, the cut cannot break a pattern.
Common mistakes
- Truncating before redacting. A partial secret can slip past the pattern, as described above.
- Sampling with
randomand no flag. You get partial request traces and cannot tell missing content from unsampled content. - Applying a single limit to everything. A 2,000-character prompt cap is reasonable. The same cap on a retrieved-documents field can hide the part you needed. Set limits per field.
- Truncating the serialized JSON. The result is an invalid line that parsers reject.
- Treating truncation as security. A short record can still contain a full email address or a name. Truncation limits the damage. It does not make the content safe.
Exercise
A request makes three LLM calls with the IDs req-9:a, req-9:b, and req-9:c, and you sample at 10% by hashing each call's ID. Your teammate finds that some requests have content logged for only one or two of the three calls. Why does this happen, and how do you change the code so that all three calls get the same decision?
Show answer
Each call ID is hashed separately, so each call gets an independent decision. Hash a value shared by all calls in the request instead, for example req-9 (the request ID without the per-call suffix). Call should_sample("req-9", 0.10) for every call in that request. They then fall into the same bucket and are all sampled in or all sampled out.
Exercise
A function runs truncate(response, 2000) and then redact(...) on the result. A response has an API key that starts at character 1,990 and ends at character 2,013. What ends up in the log, and what is the fix?
Show answer
The truncation keeps characters up to 2,000, so the log holds only the first 10 characters of the key. That fragment is shorter than the 16 characters the API_KEY pattern requires after the prefix, so redact does not match it and the partial key is logged. The fix is to call truncate(redact(response)): redact the full text first, then truncate. The whole key is replaced with [SECRET] before the cut.