Deployment and Consultant Notes

Logging AI Requests Without Storing Sensitive User Data

Logging AI Requests Without Storing Sensitive User Data
Learn how to log AI application requests securely by separating metadata from sensitive user content. This practical guide covers establishing safe default logging practices, implementing regex and hashing redaction helpers for necessary data samples, wrapping Anthropic API calls for centralized governance, and avoiding common failure modes like accidental prompt leaks through exception messages or downstream tracing.

The first production incident that involved our Anthropic logs was not a model failure. A support engineer opened a trace to diagnose a slow request and found a customer’s full name, email address, and a paragraph of medical history sitting in the prompt field. The log retention policy was thirty days. The data should never have been written there in the first place.

That is the moment I stopped treating “log everything” as a reasonable default for AI services. This post builds the smallest useful logging pattern that still lets you debug latency, cost, and failures while keeping sensitive user content out of persistent storage. We will define what must be logged, what must never be logged, and a concrete redaction step that sits between the application and the log sink.

As always:

Build the smallest useful version, then test what breaks.

What You Will Have Working by the End

  • A clear split between operational fields and content fields

  • A request-logging shape that records tokens, latency, model, and status without the raw prompt

  • A redaction helper that strips or hashes obvious sensitive patterns when content must be sampled

  • A minimal middleware (or wrapper) that applies the policy on every Anthropic call

  • Three realistic failure modes and how to notice them early

The goal is a log stream you can keep for weeks without turning it into a second copy of your users’ private data.

What You Actually Need From AI Logs

When an Anthropic request goes wrong, the questions you need answered are almost always operational:

  • Which model was called?

  • How long did it take?

  • How many input and output tokens were used?

  • Did the call succeed, time out, or return a 4xx/5xx?

  • Which internal feature or endpoint triggered the call?

  • What was the request ID (yours and, if available, Anthropic’s)?

You rarely need the full prompt or the full completion to answer those questions. When you do need content—for quality review or for debugging a specific structural failure—you should pull it from a controlled, short-lived store under access control, not from the general application log stream.

The Safe Default: Log Metadata, Not Content

A minimal safe record looks like this:

Python

{
  "ts": "2026-10-14T09:12:03.421Z",
  "request_id": "req_6f3a...",
  "feature": "support_triage",
  "model": "claude-sonnet-5",
  "status": "success",
  "latency_ms": 842,
  "input_tokens": 312,
  "output_tokens": 148,
  "stop_reason": "end_turn",
  "error_type": null
}

No prompt. No completion. No user identifier that can be joined back to a person without an additional authorized lookup. This record is enough to build latency dashboards, cost reports, and error-rate alerts.

When You Must Keep a Sample of Content

Sometimes you need a short-lived sample—for example, to investigate a spike in structured-output failures. In those cases apply three controls:

  1. Sampling – log content for only a small percentage of requests, or only for requests that already failed validation.

  2. Redaction – strip or hash emails, phone numbers, government IDs, and other obvious patterns before writing.

  3. Short retention and tight access – store samples in a separate bucket or table with a short TTL and restricted read permissions.

Never let “we might need it someday” become permanent full-content logging.

A Practical Redaction Helper

A documentary close-up of a screen showing Python regex redaction helpers and hashing functions for sensitive data.

Python

import hashlib
import re
from typing import Any

# Conservative patterns – extend for your domain
EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b")
PHONE_RE = re.compile(r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b")
SSN_RE = re.compile(r"\b\d{3}-\d{2}-\d{4}\b")

def hash_value(value: str, salt: str = "app-log-salt") -> str:
    """One-way fingerprint for correlation without storing the original."""
    return hashlib.sha256(f"{salt}:{value}".encode()).hexdigest()[:16]

def redact_text(text: str) -> str:
    if not text:
        return text
    text = EMAIL_RE.sub(lambda m: f"[email:{hash_value(m.group())}]", text)
    text = PHONE_RE.sub(lambda m: f"[phone:{hash_value(m.group())}]", text)
    text = SSN_RE.sub("[ssn:REDACTED]", text)
    return text

def redact_structure(obj: Any) -> Any:
    """Recursively redact strings inside dicts/lists."""
    if isinstance(obj, str):
        return redact_text(obj)
    if isinstance(obj, dict):
        return {k: redact_structure(v) for k, v in obj.items()}
    if isinstance(obj, list):
        return [redact_structure(v) for v in obj]
    return obj

Redaction is imperfect. It will miss novel patterns and context-specific secrets. That is why the default remains “do not log content at all.” Redaction is a mitigation for the minority of cases where a sample is justified.

A Wrapper That Enforces the Policy

Centralize every Anthropic call behind a small wrapper so the policy cannot be forgotten on a new code path.

A documentary photo of a developer reviewing terminal logs for centralized API wrappers and execution metadata.

Python

import logging
import time
import uuid
from anthropic import Anthropic
from anthropic import APIError

logger = logging.getLogger("anthropic.requests")

def call_anthropic(
    client: Anthropic,
    *,
    feature: str,
    model: str,
    messages: list,
    system: str | None = None,
    max_tokens: int = 512,
    log_content_sample: bool = False,
    **kwargs
) -> any:
    request_id = str(uuid.uuid4())
    start = time.perf_counter()
    status = "success"
    error_type = None
    response = None

    try:
        response = client.messages.create(
            model=model,
            max_tokens=max_tokens,
            system=system,
            messages=messages,
            **kwargs
        )
        return response
    except APIError as e:
        status = "error"
        error_type = type(e).__name__
        raise
    finally:
        latency_ms = (time.perf_counter() - start) * 1000
        record = {
            "request_id": request_id,
            "feature": feature,
            "model": model,
            "status": status,
            "latency_ms": round(latency_ms, 1),
            "error_type": error_type,
        }
        if response is not None:
            record["input_tokens"] = response.usage.input_tokens
            record["output_tokens"] = response.usage.output_tokens
            record["stop_reason"] = response.stop_reason

        if log_content_sample:
            # Only when explicitly requested – still redacted
            record["messages_redacted"] = redact_structure(messages)
            if system:
                record["system_redacted"] = redact_text(system)

        logger.info("anthropic_request", extra={"anthropic": record})

Every call site passes a feature name. The wrapper guarantees that the operational fields are always present and that content is absent unless a deliberate sample is requested.

Wiring It into a Service

Python

from fastapi import FastAPI
from pydantic import BaseModel
from .workflow import get_client
from .logging_wrapper import call_anthropic

app = FastAPI()
client = get_client()

class TriageRequest(BaseModel):
    ticket_text: str

@app.post("/triage")
def triage(body: TriageRequest):
    response = call_anthropic(
        client,
        feature="support_triage",
        model="claude-sonnet-5",  # verify current ID in official docs
        system="Return a short triage summary.",
        messages=[{"role": "user", "content": body.ticket_text}],
        max_tokens=300,
        log_content_sample=False  # default: metadata only
    )
    return {"summary": response.content[0].text}

New endpoints inherit the same policy automatically. There is no separate “remember to sanitize the logs” step for each feature.

Three Failure Modes Worth Testing

1. Content Leaks Through Exception Messages

An exception handler that does logger.exception("Failed for prompt: %s", prompt) will write the very data you are trying to protect. Confirm that no exception path interpolates raw user content into the log message. The wrapper’s finally block should be the only place that emits the request record.

2. Debug Flags Left On in Production

A log_content_sample=True flag that was useful during a staging investigation gets deployed to production and stays on. Gate the flag behind an explicit configuration value that defaults to False, and alert when the rate of content-bearing log lines rises above a tiny threshold.

3. Downstream Systems Re-hydrate the Prompt

A metrics or tracing system that automatically captures HTTP bodies, or an error tracker that records request payloads, can re-introduce the prompt after you have removed it from your own logs. Review the data each connected system stores and disable body capture for routes that handle user content.

Practical Rules That Keep Logs Safe

  • Default to metadata only. Require an explicit, reviewable decision to log any content.

  • Prefer short-lived, access-controlled sample stores over the main application log for any content you do keep.

  • Redact before write, not after. Once a secret is in a durable log stream it is already a retention and access problem.

  • Include a stable request_id so you can join operational logs to a separate, authorized content store when a real investigation requires it.

  • Review log lines from a fresh production deployment the same day you ship; the first day is when accidental content logging is easiest to catch.

What This Logging Approach Does Not Solve

It does not:

  • Replace proper access control on the application itself

  • Guarantee that every possible sensitive pattern is redacted

  • Satisfy every regulated-industry retention requirement by itself

  • Provide full prompt-level debugging without additional authorized tooling

Those concerns belong to broader security and compliance work. The goal today is a logging default that does not create a second, less-protected copy of user data.

Verification Checklist

  1. Send a request that contains an email address and a phone number; confirm the standard log line contains only metadata.

  2. Enable a content sample for a single request; confirm the stored sample has the email and phone redacted or hashed.

  3. Force an Anthropic API error; confirm the error log still contains no raw prompt.

  4. Search the log store for a known customer email; confirm zero hits under the default policy.

  5. Confirm every Anthropic call site in the codebase goes through the shared wrapper (no direct client.messages.create calls that bypass logging policy).

If all five steps pass, you have a working, privacy-preserving request log.

Update Note

Anthropic response fields (usage, stop_reason, etc.) remain stable. Model identifiers change; always verify the current recommended ID in the official documentation. Log-sink and observability-vendor behavior changes more frequently—re-check body-capture settings whenever you adopt a new tool.

Looking Ahead

The next post gathers the operational and safety checks from this deployment series into a single production-readiness checklist for Anthropic applications. Once secrets are injected safely and logs no longer retain sensitive content, the remaining work is confirming that the system as a whole is ready for real traffic.

Keep the metadata-only default. When a later incident requires prompt-level inspection, you will already have a clean operational trail and a deliberate, narrow path for content samples instead of a thirty-day archive of everything users typed.

Build the smallest useful version, then test what breaks.

— Caleb Fletcher

Boise, Idaho

Updated · 2026-10-21 10:07
Feedback

No feedback yet — submit the first.

Submit feedback
© 2026 Context & Tools. All rights reserved. data-driven, published weekly ♥