Sub topic 8
Redacting PII and secrets from logged text
This chapter assumes you can write basic Python, use regular expressions, and call an LLM API. It also assumes you know how application logging and log levels work. By default, your logs hold metadata only. Redaction applies to the smaller amount of text you choose to log on top of that.
What redaction does
Redaction replaces sensitive substrings with placeholders before text reaches a log. PII (personally identifiable information) is data that identifies a person, such as an email address or phone number. Secrets are credentials such as API keys and tokens.
Redaction is a second line of defense. Your policy decides whether to log content at all. Redaction reduces the damage when you do.
A pattern-based redactor
The simplest redactor uses regular expressions. Each pattern matches one kind of sensitive value and swaps it for a labeled placeholder.
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
print(redact("Mail [email protected], key sk-abcdefghijklmnop1234"))
# Mail [EMAIL], key [SECRET]The placeholders name the category. A reader of the log can still see that an email was present, which helps debugging, without seeing the address.
Where patterns fall short
Patterns catch common formats. They never catch everything. Typical gaps include:
- Names and street addresses, which have no fixed format.
- Keys from providers whose prefix your pattern does not list.
- Values split by whitespace or encoded, such as base64 or URL-escaped text.
- Sensitive facts written in plain prose, such as "my diagnosis is...".
Over-matching also happens. A loose pattern can hide harmless text and make logs less useful. Tune patterns against real samples, and keep them narrow.
Order of operations
Apply redaction before truncation. If you cut the text first, a key could be split so that your pattern no longer matches its remaining half, and that half would reach the log. In the wrapper below, redact(prompt)[:2000] redacts the whole string and then truncates.
Redact on every path that writes content. That includes prompts, responses, error messages, and any extra fields you attach to a record. A single unredacted field defeats the rest of the work.
Using redaction in the call wrapper
The wrapper from the previous chapters logs metadata always and content only when log_content is true. Redaction sits inside that gated branch.
import hashlib
import json
import logging
import time
import uuid
logger = logging.getLogger("llm")
def call_logged(client_call, model: str, prompt: str, log_content: bool = False) -> str:
record = {
"event": "llm_call",
"request_id": str(uuid.uuid4()),
"model": model,
"prompt_chars": len(prompt),
"prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
}
start = time.perf_counter()
try:
response = client_call(model=model, prompt=prompt)
record["status"] = "ok"
record["response_chars"] = len(response)
if log_content:
record["prompt"] = redact(prompt)[:2000]
record["response"] = redact(response)[:2000]
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))The error path logs only the exception class name, not its message. Exception messages can echo the prompt or a credential, so they are a common leak.
Grow the redactor from real misses
Each time you find a leak in a log, add a pattern and a test for it. The next chapters cover testing, but the habit starts here: treat every miss as a new test case.
Exercise
Why should you call redact() before slicing the text to 2000 characters, and not after?
Show answer
Truncating first can cut a secret in half, so the pattern no longer matches either piece and part of the secret is logged. Redacting the full text first replaces the whole secret, and truncation then only shortens the already safe text.
Exercise
Name two kinds of sensitive data that the EMAIL and API_KEY patterns above would miss.
Show answer
Examples include personal names or street addresses, phone numbers, keys with prefixes other than sk, key, or token, and encoded values such as base64 text. Any two of these are correct.