Sub topic 12
Logging streamed responses safely
This chapter assumes you can call an LLM API with streaming, use Python generators, and have read the earlier chapters on metadata-first logging and redaction. It builds on the redact function from the redaction chapter.
Why streaming changes logging
A non-streaming call returns one string, so you can redact it and log it once. A streamed call delivers many small chunks. Two problems follow.
- Split secrets. A key such as
sk-abcdefghijklmnop1234can arrive across two chunks. Redacting each chunk alone finds no match in either half, so the secret passes through. - Partial records. If you log every chunk, one response becomes dozens of log lines. They are hard to read and expensive to store. They also expose text before you have checked it.
The fix is to pass chunks to the caller unchanged, collect them, and write one log record at the end.
A logging wrapper for streams
This generator wrapper yields each chunk immediately, so the user sees no delay. The finally block runs when the stream finishes, when an error occurs, and when the consumer stops early.
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]})
fake_stream = ["Mail ana@exam", "ple.com, key sk-abcdefgh", "ijklmnop1234"]
for piece in stream_logged(fake_stream, print):
pass
# {'event': 'llm_stream_done', 'response_chars': 51, 'response': 'Mail [EMAIL], key [SECRET]'}The email and the key were each split across chunks. Joining first and redacting second catches both.
Details that matter
- Redact after joining, then truncate. Truncate last. If you cut the text first, you can slice a secret in half so that the pattern no longer matches, and a fragment is logged.
- Log on early exit. Users cancel streams. A
finallyblock covers cancellation, because closing a generator raisesGeneratorExitinside it. Add a field such as"completed": Falseif you need to tell the cases apart. The simple wrapper above does not do this. - Log metadata even when content is off. In metadata-only mode, keep
response_chars, status, latency, and the request ID. Skip theresponsefield unless content logging is enabled for this request. - Bound the buffer. A very long stream held in memory is a risk. Stop appending after a limit, such as 100,000 characters, and record that the text was cut. Redact only what you kept.
- Keep timing fields. For streams, time to first chunk is often more useful than total latency. Record it with
time.perf_counter()when the first chunk arrives.
What redaction cannot promise
A pattern-based redactor catches common formats and misses the rest. A name, an address, or a password written in plain prose will not match an email or key pattern. Streaming adds no new weakness here, but it does make you tempted to log early. Treat content logging as an exception, as the logging policy chapter describes. Turn it on for specific requests, for a limited time.
Exercise
A stream delivers the chunks "sk-abcdefgh" and "ijklmnop1234". Why does redacting each chunk separately fail to hide the key, and what should the wrapper do instead?
Show answer
Each chunk alone is too short to match the key pattern, which needs 16 or more characters after the prefix, so both pass through unredacted. The wrapper should pass chunks to the caller as they arrive, join them in a buffer, then redact and truncate the joined text once when the stream ends or stops, and log a single record.
Exercise
Why is the log call placed in a finally block, and why should truncation happen after redaction?
Show answer
The finally block runs on normal completion, errors, and early cancellation, so every stream produces a record. Truncating after redaction prevents a cut from slicing a secret in half, which would stop the pattern from matching and leave a fragment in the log.