Safe Logging, Sampling and Retention
Telemetry that explains an agent can also expose its users. Collect with purpose, protect it and delete it.
Split telemetry into metadata, content and audit records. Keep metadata for most runs, capture content only for a stated reason, allow-list fields and redact before storage, sample so that failures are kept, restrict access, and give every class a retention period that deletion actually enforces.
What you will learn: what to log from prompts, responses and tool calls, redaction and its limits, sampling strategies, retention classes, legal duties that pull in different directions and how to prove deletion.
Prerequisites: Agent Tracing and OpenTelemetry. PII Redaction and Data Leakage Prevention covers protection of personal data in detail.
The example runs in November 2026 with Python 3.13 and only the standard library. Its retention periods and sampling rate are placeholders, not recommendations. Legal points are general information, not legal advice.
Three classes of record
| Class | Contains | Used for | Typical handling |
|---|---|---|---|
| Metadata | IDs, versions, timings, token counts, tool names, status | Health, cost and trends | All runs, broad engineering access |
| Content | Prompts, replies, retrieved text, tool arguments and results | Debugging and quality review | Selected runs, narrow access, short life |
| Audit and security | Who did what, policy decisions, approvals, changes | Accountability and investigation | Complete, protected, defined period |
Keeping them apart lets you give each its own access and deletion rules. Mixed together, the strictest need and the loosest habit collide.
What hides in content
| Source | May contain |
|---|---|
| User messages | Names, health or money details, passwords typed by mistake |
| System prompts | Internal rules and, if badly built, keys |
| Retrieved passages | Confidential documents, other people's data |
| Tool arguments and results | Whole records, tokens, addresses |
| Error messages | Connection strings, query text, stack traces |
| Files and images | Anything at all, including text that scanners miss |
Logs are also an attack surface. Text from outsiders may contain instructions aimed at a person or a model that later reads the logs, or markup aimed at the viewer. Escape it on display and treat any automated log analyst as exposed to Prompt Injection Attacks and Defenses.
Apply protection in the right order
An allow list states the fields that may pass. A deny list names fields to remove and silently lets every new field through. Start with the allow list; use pattern redaction as a second net for the free text you choose to keep.
A telemetry policy in code
"""Decide what to keep, for how long, before anything is stored."""
import hashlib
import re
from datetime import date, timedelta
ALLOWED = {"run_id", "agent_version", "tool", "status", "latency_ms",
"tokens", "tenant", "error_type", "detail"}
RETENTION_DAYS = {"metadata": 180, "content": 14, "security": 365} # examples only
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
LONG_NUMBER = re.compile(r"\b(?:\d[ -]?){12,18}\d\b")
SECRET = re.compile(r"\b(?:sk|key|token)[-_][A-Za-z0-9]{8,}\b")
def scrub(text):
for pattern, label in ((SECRET, "[secret]"), (EMAIL, "[email]"),
(LONG_NUMBER, "[number]")):
text = pattern.sub(label, text)
return text
def clean(event):
"""Allow-list fields first, then scrub what free text remains."""
kept = {k: v for k, v in event.items() if k in ALLOWED}
if "detail" in kept:
kept["detail"] = scrub(str(kept["detail"]))[:200]
return kept, sorted(set(event) - ALLOWED)
def keep_content(run, percent=10):
"""Tail decision: made after the run, when the outcome is known."""
if run["outcome"] != "ok":
return True, "failed run"
if run.get("policy_block"):
return True, "policy block"
bucket = int(hashlib.sha256(run["run_id"].encode()).hexdigest(), 16) % 100
return bucket < percent, f"sample bucket {bucket}"
def expires(kind, day):
return day + timedelta(days=RETENTION_DAYS[kind])
event = {"run_id": "r-101", "tool": "crm.update", "status": "error",
"latency_ms": 912, "prompt": "full customer message here",
"detail": "Rejected for ana@example.com card 4111 1111 1111 1111 "
"using token_A1b2C3d4E5"}
kept, dropped = clean(event)
print("Stored detail:", kept["detail"])
print("Dropped fields:", dropped)
runs = [{"run_id": "r-101", "outcome": "error"},
{"run_id": "r-102", "outcome": "ok", "policy_block": True},
{"run_id": "r-103", "outcome": "ok"},
{"run_id": "r-104", "outcome": "ok"}]
for run in runs:
yes, why = keep_content(run)
print(run["run_id"], "keep content" if yes else "metadata only", f"({why})")
day = date(2026, 11, 28)
for kind in RETENTION_DAYS:
print(f"{kind:9} delete after {expires(kind, day)}")
Output:
Stored detail: Rejected for [email] card [number] using [secret]
Dropped fields: ['prompt']
r-101 keep content (failed run)
r-102 keep content (policy block)
r-103 metadata only (sample bucket 42)
r-104 metadata only (sample bucket 32)
metadata delete after 2027-05-27
content delete after 2026-12-12
security delete after 2027-11-28
The prompt field never reaches storage because it is not on the allow list. The error detail survives with three patterns masked. The failed run and the blocked run keep content; the two ordinary runs fell outside the 10 percent sample. Sampling uses a hash of the run ID, so every service that applies the same function makes the same choice.
These patterns miss names, addresses, unusual number formats, other languages and secrets with different shapes. They can also mask harmless text. Measure detection on realistic test data and assume stored content may still be sensitive.
Ways to protect a value
| Method | Can you correlate? | Can you recover it? | Note |
|---|---|---|---|
| Remove | No | No | Safest when unneeded |
| Mask | No | No | Keeps readability |
| Keyed hash | Yes | Not directly | Still personal data if you can link it; protect the key |
| Tokenize with a vault | Yes | Yes, with permission | The vault becomes critical |
| Encrypt | Depends | Yes, with the key | Deleting the key can make copies unreadable |
A plain hash of an email address or phone number can often be reversed by guessing inputs, so use a keyed method.
Sampling strategies
| Strategy | Decision made | Good | Cost |
|---|---|---|---|
| Head sampling | At the start | Simple and cheap; consistent across services | Cannot know the run will fail |
| Tail sampling | After the run | Keeps errors, slow and costly runs | Must buffer data and route a trace to one decision point |
| Rule-based | By attribute | Keeps high-risk actions or new versions | Rules need upkeep |
| Random review sample | Across normal runs | Finds quiet failures | Needs reviewers |
Combine them: all metadata; all errors, blocks, escalations and complaints; a higher share for new releases; and a small random sample of the rest. Record the sampling rate with the data, or later counts will mislead. Compute rates and totals from unsampled metrics.
Tail sampling holds content briefly before deciding, so that buffer is also storage: protect it, bound it and clear it.
Log tool calls field by field
Tool calls are where logging is most useful and most risky. Decide per tool, because a search query and a payment instruction need different treatment.
| Item | Log | Avoid |
|---|---|---|
| Identity | Tool name and version, call ID, pseudonymous user | Access tokens, cookies, raw credentials |
| Arguments | Declared safe fields, record identifiers, amounts needed for audit | Whole request bodies |
| Result | Status, error class, count, size, identifiers changed | Full records returned |
| Policy | Rule, decision, reason, approval ID | Nothing: this is usually safe and valuable |
| Timing | Start, duration, attempts | No special concern |
Put the classification in the tool's definition, next to its schema, so that adding a field forces a decision about logging it. A test can fail when a new field has no label (Designing Tool Schemas and Contracts).
Log prompts by reference
Most of a prompt is fixed text. Record the template identifier and version plus the identifiers of retrieved documents and memories. With version control and access to the sources, you can often rebuild what the model saw without storing another copy of it. Note where that fails: documents that changed or were deleted cannot be rebuilt, so record version numbers or hashes.
Test the filters
- Keep a set of invented sensitive values in several formats and languages, and assert they never appear in exported telemetry.
- Include error paths, since exceptions often print raw input.
- Check libraries' debug modes, web server logs and crash reports, which bypass your pipeline.
- Fail the build when a new unclassified field appears.
- Sample stored data periodically for leaks, with strict access, and fix the source.
Set retention from purposes and duties
- List the purposes for each class: debugging, quality, security, audit, billing, legal.
- Find minimum periods required by law or contract.
- Find maximum periods implied by privacy duties and promises.
- Choose the shortest period that serves the purposes and meets the minimums.
- Define legal holds: who may pause deletion, for what and for how long.
- Automate expiry and check it.
Duties can pull in two directions
Under the EU AI Act, deployers of high-risk AI systems keep the automatically generated logs under their control for a period suited to the purpose, at least six months unless other law provides otherwise. Under the General Data Protection Regulation, personal data should be limited to what is necessary and not kept longer than needed. The two can be reconciled by design: keep the events the law needs, with identifiers and decisions, and avoid putting full content into them; expire optional debugging content much sooner. The high-risk duties have later application dates, so check which apply to you and when (EU AI Act and US AI Policy). Sector rules may require longer periods.
| Record | Question that sets the period |
|---|---|
| Debug content | How long after a run do you realistically investigate it? |
| Quality samples | When is review finished and the case turned into a clean test? |
| Security events | How late are intrusions typically discovered in your threat model? |
| Approvals and actions | How long can the action be disputed or audited? |
| Metrics | How far back do you compare trends? Do they hold personal data? |
Control and record access
- Separate roles for metadata, content and audit data.
- Require a reason or ticket to open content, and log the access.
- Prefer a view that shows masked values with a controlled way to reveal one.
- Block bulk export by default.
- Keep tenants separate and test the separation.
- Apply the same rules to copies sent to vendors, notebooks and evaluation sets.
Make deletion real
A retention setting in one tool does not delete copies elsewhere. Map them: collector buffers, queues, primary store, search index, backups, exports, evaluation datasets, support tickets and supplier systems.
| Check | How |
|---|---|
| Expiry runs | Alert if the deletion job fails or deletes nothing for too long |
| Nothing older remains | Query for records past their date every week |
| Planted marker | Create a fake record, delete it, then search every copy |
| Backups | Document how long they persist and what happens on restore |
| Individual requests | Index runs by a pseudonymous user key so they can be found |
Debug without seeing everything
- Record lengths, counts, hashes and schema validation results instead of values.
- Store identifiers of documents and records, then open the source under its own access rules.
- Turn on detailed capture for one test user or a short window, with approval and automatic expiry.
- Reproduce with synthetic data once the shape of the fault is clear (Debugging Agents, RAG and Handoffs).
- Ask the user for consent to attach a conversation to a support case.
Suppliers see logs too
Model providers, tracing services and tool vendors may retain prompts and results under their own terms. Check retention, training use, location, subprocessors and deletion support, and set options deliberately rather than relying on defaults. List every destination in your data map.
Control volume and cost
Agent traces can be large, because context is repeated at every model call. Store a content item once and reference it by hash, truncate with a visible marker, cap attribute sizes, move large objects to protected object storage and watch ingestion by agent version. A sudden jump in volume is itself a signal of loops or a bloated prompt. Never let a size limit silently drop an audit event.
A one-page logging decision record
For each agent, write down what is captured, why, where it goes, who can read it, how long it lasts, how it is deleted and who approved those choices. Add the sampling rules and the switch that turns detailed capture on and off. Review the page when a tool, data type, supplier or country changes. It gives engineers a specification, privacy staff something concrete to assess and auditors a statement they can test against the running system. If the record and the system disagree, treat that as a defect and fix whichever is wrong. Keep earlier versions of the record, so that you can show which rules applied when a particular piece of data was collected and who had agreed to them.
Common mistakes
| Mistake | Better approach |
|---|---|
| Logging whole requests "for now" | Opt in to content with an end date |
| Redacting after storage | Filter before data leaves the service |
| Deny lists only | Allow-list fields |
| Random sampling that loses failures | Always keep errors and high-risk events |
| Sampling audit records | Keep in-scope events completely |
| One retention period for everything | Set it by class and duty |
| Assuming deletion works | Test with planted records |
Safe logging checklist
- Records are separated into metadata, content and audit.
- Each captured field has a purpose.
- Allow lists and redaction run before storage.
- Secrets never enter prompts or logs by design.
- Sampling keeps failures, blocks and complaints.
- Content access is limited and recorded.
- Retention is set from duties and enforced automatically.
- Deletion is tested across every copy, including suppliers.
Frequently asked questions
Should we log full prompts and responses?
Only where a stated purpose needs them, on selected runs, with protection and a short life.
Is hashed data anonymous?
Usually not if it can still be linked to a person, so keep treating it as personal data.
What sampling rate should we use?
Start from how many normal runs you can review and afford, while keeping every failure and high-risk event.
Can debug logs serve as the audit trail?
Not safely, because audit records need completeness, protection and retention that debug data normally lacks.
References and further reading
- OWASP Logging Cheat Sheet: what to log and what to exclude.
- AI Act Service Desk: Article 26: deployer log retention.
- General Data Protection Regulation: minimization and storage limitation.
- OpenTelemetry: sampling: head and tail sampling.
- OpenTelemetry: handling sensitive data: protecting telemetry.
Next steps
Debugging Agents, RAG and Handoffs
Investigate with what you kept.
Human Approval, Thresholds and Secure Logging
Make audit records tamper-evident.
Data Contracts, Access and Retention
Apply the same rules to knowledge data.