Sub topic 12
Logging streamed responses safely
Streaming sends a model's answer in many small chunks instead of one response. This changes what you can log and when. This chapter covers how to log a stream without leaking partial or unredacted text.
It assumes you can call an LLM API with streaming enabled and know Python generators. It also assumes you have read the earlier chapters on the metadata-first policy and on redaction. The wrapper here reuses the redact function from those chapters.
Why streams need their own logging approach
A non-streamed call has one clear moment to log: the response comes back, and you write one record. A stream has no such moment. Chunks arrive over seconds, and the caller may stop reading at any time. The connection can also fail halfway through.
The obvious fix is to log each chunk as it arrives. That creates four problems:
- Secrets split across chunks. A redaction pattern needs the whole email address or key in one string. A chunk boundary can fall in the middle of it, and neither half matches.
- Many records for one call. A single answer can produce hundreds of log lines, which are hard to query and expensive to store.
- No outcome. Per-chunk lines carry no final status, total size, or latency.
- Partial text. Half a sentence in a log is hard to read. It can also leak a prefix of a secret that no pattern recognizes.
The rule for this chapter is to pass chunks through untouched and log once, at the end, from a buffer.
The basic wrapper
The wrapper below is a generator. It passes each chunk to the caller as it arrives, so the user sees no added delay. It also keeps a copy of the chunks. The finally block runs when the stream ends normally. It also runs when the caller stops early or an error occurs.
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 stream_logged(chunks, log_fn):
parts = []
try:
for chunk in chunks:
parts.append(chunk)
yield chunk
finally:
text = "".join(parts)
log_fn({"event": "llm_stream_done", "response_chars": len(text), "response": redact(text)[:2000]})
def fake_stream():
yield "Contact ana@exam"
yield "ple.com or use sk-abcdefgh"
yield "ijklmnop1234 today."
records = []
shown = "".join(stream_logged(fake_stream(), records.append))
print(shown)
print(records[0]["response"])
print([redact(c) for c in fake_stream()])The program prints three lines:
Contact [email protected] or use sk-abcdefghijklmnop1234 today.
Contact [EMAIL] or use [SECRET] today.
['Contact ana@exam', 'ple.com or use sk-abcdefgh', 'ijklmnop1234 today.']The first line is what the caller saw. The wrapper never alters the stream. Redaction applies only to the log copy. The second line is the log record, redacted after the chunks were joined. The third line shows the failure the wrapper avoids. Redacting each chunk alone leaves both the email address and the key intact, because neither is complete in any single chunk.
Redact first, then truncate
The spine example calls redact(text)[:2000], which puts redaction before truncation. The order matters. If you cut the text to 2,000 characters first, the cut can land inside a key. The key's first 12 characters would no longer match a 16-character pattern, so they would be logged as they are. Redacting the full text and then cutting it never leaves a half-secret.
Bounding memory and handling truncation
A model can produce very long output, and a buffer that holds all of it uses memory for every concurrent stream. Cap the buffer. Keep a running character count separate from the stored text, so the logged size stays accurate.
Capping brings the half-secret problem back. If you stop storing at 20,000 characters, the stored text may end in the middle of a key. The fix is a tail guard. When the buffer was capped, drop the last few dozen characters before redacting.
A production-shaped wrapper
This version adds the metadata the earlier chapters call for: status, chunk count, time to first chunk, and total latency. It also adds a memory cap and the tail guard.
import time
MAX_BUFFER = 20_000
TAIL_GUARD = 64
def stream_logged_full(chunks, log_fn, log_content=False):
parts = []
stored = 0
total = 0
count = 0
status = "ok"
error_type = None
first_chunk_ms = None
start = time.perf_counter()
try:
for chunk in chunks:
if first_chunk_ms is None:
first_chunk_ms = round((time.perf_counter() - start) * 1000)
count += 1
total += len(chunk)
if log_content and stored < MAX_BUFFER:
piece = chunk[: MAX_BUFFER - stored]
parts.append(piece)
stored += len(piece)
yield chunk
except GeneratorExit:
status = "cancelled"
raise
except Exception as exc:
status = "error"
error_type = type(exc).__name__
raise
finally:
record = {
"event": "llm_stream_done",
"status": status,
"chunks": count,
"response_chars": total,
"first_chunk_ms": first_chunk_ms,
"latency_ms": round((time.perf_counter() - start) * 1000),
}
if error_type:
record["error_type"] = error_type
if log_content:
text = "".join(parts)
if total > stored:
text = text[:-TAIL_GUARD]
record["response"] = redact(text)[:2000]
log_fn(record)Points to notice in this wrapper:
- Content is opt-in. With
log_content=False, the default, nothing is buffered and no text reaches the log. This follows the metadata-first policy. - Three statuses.
GeneratorExitis raised inside the generator when the consumer callsclose()or stops iterating and the generator is cleaned up. The record showscancelled, notok. A cancelled stream is not an error, but cost and latency reports should be able to tell it apart. - Errors still reach the caller. Both
exceptblocks re-raise. A logging wrapper must not swallow exceptions. - Time to first chunk is separate. For a stream,
first_chunk_msis often the number users feel, whilelatency_msmeasures the whole answer. - The log call should not fail the request. In real code, wrap
log_fn(record)in its owntry/exceptso a logging outage does not break a response the user is reading.
Token counts and other end-of-stream data
Many APIs report token usage only in the last chunk of a stream, or only if you request it with a stream option. Check your provider's documentation. If usage arrives, copy the numbers into the record. If it does not, do not estimate them silently. Log response_chars and leave the token fields empty, so cost reports can see which records are measured and which are missing.
Failure modes
| Situation | What goes wrong | What the wrapper does |
|---|---|---|
| Secret split across chunks | Per-chunk redaction misses it | Redacts the joined text |
| Caller disconnects early | No final record is written | `finally` logs with status `cancelled` |
| Provider error mid-stream | Partial text with no outcome | Logs status `error` and the exception type, then re-raises |
| Very long output | Buffer grows without limit | Caps the buffer and drops a tail guard |
| Generator never started | `finally` never runs, so no record exists | Not covered by the wrapper. Add a request-start log line if you need it |
| Model text contains newlines | Forged log lines | Serialize with `json.dumps` before writing |
The last row repeats a rule from the earlier chapter on log injection. Streamed text is untrusted like any other model output, so write the record as a JSON string and never as interpolated text.
Testing stream logging
Add tests for the cases above. The first test checks that a secret split across chunks does not reach the log. The second checks that stopping early records cancelled.
def test_stream_secret_split_across_chunks():
records = []
chunks = ["key sk-abcdefgh", "ijklmnop1234 ok"]
list(stream_logged_full(iter(chunks), records.append, log_content=True))
assert "sk-abcdefghijklmnop1234" not in records[0]["response"]
assert "[SECRET]" in records[0]["response"]
def test_stream_early_stop_is_cancelled():
records = []
gen = stream_logged_full(iter(["a", "b", "c"]), records.append)
next(gen)
gen.close()
assert records[0]["status"] == "cancelled"
assert records[0]["chunks"] == 1
assert "response" not in records[0]The second test also confirms that no content is logged when log_content is off. Run both tests whenever you change a pattern or the wrapper.
Summary of rules
- Forward chunks unchanged. Log from a copy.
- Buffer, join, redact, then truncate. Never in another order.
- Write one record per stream, from a
finallyblock. - Record
ok,cancelled, orerror, plus chunk count and time to first chunk. - Cap the buffer, and drop a tail guard when the cap is hit.
- Keep content logging off by default.
Exercise
Your wrapper stores chunks until it reaches 20,000 characters, then stops storing. A long answer ends with a key that begins at character 19,990. Why might the logged text still leak part of that key, and what change prevents it?
Show answer
Only the first 10 characters of the key are stored. That fragment is shorter than the 16-character minimum in the key pattern, so redaction does not match it and the fragment is logged as it is. Dropping the last N characters (a tail guard, such as 64) from the stored text whenever the buffer was capped removes the fragment before redaction.
Exercise
A teammate wants to log each chunk as it arrives so the logs show text in real time. Give two reasons to refuse and one safer way to get live visibility.
Show answer
Redaction patterns fail when a secret or email address is split across chunks, so per-chunk logging can leak it. It also produces many records per call with no final status or latency. For live visibility, log metadata only, such as a start event and counters like chunks received so far, and keep text for the single end-of-stream record.