Safe Logging, Sampling and Retention

Telemetry that explains an agent can also expose its users. Collect with purpose, protect it and delete it.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Versions used

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.

Beginner Know what you are storing

Three classes of record

ClassContainsUsed forTypical handling
MetadataIDs, versions, timings, token counts, tool names, statusHealth, cost and trendsAll runs, broad engineering access
ContentPrompts, replies, retrieved text, tool arguments and resultsDebugging and quality reviewSelected runs, narrow access, short life
Audit and securityWho did what, policy decisions, approvals, changesAccountability and investigationComplete, 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

SourceMay contain
User messagesNames, health or money details, passwords typed by mistake
System promptsInternal rules and, if badly built, keys
Retrieved passagesConfidential documents, other people's data
Tool arguments and resultsWhole records, tokens, addresses
Error messagesConnection strings, query text, stack traces
Files and imagesAnything 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.

Intermediate Filter, sample, expire

Apply protection in the right order

Captureonly what has a purpose
Allow-listdrop unknown fields
Redactmask what remains
Samplekeep what matters
Store and expireby class

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.

Redaction is not a guarantee

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

MethodCan you correlate?Can you recover it?Note
RemoveNoNoSafest when unneeded
MaskNoNoKeeps readability
Keyed hashYesNot directlyStill personal data if you can link it; protect the key
Tokenize with a vaultYesYes, with permissionThe vault becomes critical
EncryptDependsYes, with the keyDeleting 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

StrategyDecision madeGoodCost
Head samplingAt the startSimple and cheap; consistent across servicesCannot know the run will fail
Tail samplingAfter the runKeeps errors, slow and costly runsMust buffer data and route a trace to one decision point
Rule-basedBy attributeKeeps high-risk actions or new versionsRules need upkeep
Random review sampleAcross normal runsFinds quiet failuresNeeds 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.

ItemLogAvoid
IdentityTool name and version, call ID, pseudonymous userAccess tokens, cookies, raw credentials
ArgumentsDeclared safe fields, record identifiers, amounts needed for auditWhole request bodies
ResultStatus, error class, count, size, identifiers changedFull records returned
PolicyRule, decision, reason, approval IDNothing: this is usually safe and valuable
TimingStart, duration, attemptsNo 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.
Expert Retention, access and proof

Set retention from purposes and duties

  1. List the purposes for each class: debugging, quality, security, audit, billing, legal.
  2. Find minimum periods required by law or contract.
  3. Find maximum periods implied by privacy duties and promises.
  4. Choose the shortest period that serves the purposes and meets the minimums.
  5. Define legal holds: who may pause deletion, for what and for how long.
  6. 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.

RecordQuestion that sets the period
Debug contentHow long after a run do you realistically investigate it?
Quality samplesWhen is review finished and the case turned into a clean test?
Security eventsHow late are intrusions typically discovered in your threat model?
Approvals and actionsHow long can the action be disputed or audited?
MetricsHow 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.

CheckHow
Expiry runsAlert if the deletion job fails or deletes nothing for too long
Nothing older remainsQuery for records past their date every week
Planted markerCreate a fake record, delete it, then search every copy
BackupsDocument how long they persist and what happens on restore
Individual requestsIndex 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

MistakeBetter approach
Logging whole requests "for now"Opt in to content with an end date
Redacting after storageFilter before data leaves the service
Deny lists onlyAllow-list fields
Random sampling that loses failuresAlways keep errors and high-risk events
Sampling audit recordsKeep in-scope events completely
One retention period for everythingSet it by class and duty
Assuming deletion worksTest 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

Next steps