CertSafari
    Anthropic Claude Certified Architect – Professional (CCAR-P)· Lessons

    Domain 4 · Lesson 25/38

    OpenTelemetry for Claude Code and the Agent SDK: signals, traces and content gates

    Monitor system performance using logging and observability tools

    13 min read
    2.67% of exam
    3 sources
    Published 19 Oct 2026
    Docs as of 14 Oct 2026

    What you will be able to do

    • Wire metrics, log events and traces from Claude Code or the Agent SDK to an OTLP collector, and explain why enabling telemetry alone exports nothing
    • Choose a backend type suited to each signal and control metric attributes such as session.id to manage cardinality
    • Read a trace to find where a run spent its time and tokens, including subagent spans
    • State what telemetry redacts by default and which variable reveals prompts, responses, tool details, tool output or raw API bodies

    Key concept

    Three opt-in OpenTelemetry signals — Claude Code and the Agent SDK emit three separate signals: metrics (counters), log events (one structured record per thing that happened) and traces (timed spans). Each signal has its own exporter variable, and a signal with no exporter never leaves the process, whatever else you turn on.

    1.Metrics, log events and traces answer different questions

    Monitoring an agent in production comes down to three questions. How much are we using, and what does it cost? What exactly happened on this request? Where did this run spend its time? Claude Code and the Agent SDK answer each one with a different OpenTelemetry signal, and each signal has its own exporter. Metrics are counters for tokens, cost, sessions, lines of code and tool decisions, so they suit totals and rates. Log events are structured records for each prompt, API request, API error and tool result, so they answer "what happened". Traces are spans for each interaction, model request, tool call and hook, so they show where the time went.

    Each signal, how it is enabled, and the backend types it suits
    SignalEnable withSuited backends
    MetricsOTEL_METRICS_EXPORTER (otlp, prometheus, console, none)Time series databases for rate calculations and aggregated metrics; columnar stores for complex queries and unique-user analysis
    Log eventsOTEL_LOGS_EXPORTER (otlp, console, none)Log aggregation systems for full-text search and log analysis; columnar stores for structured event analysis
    Traces (beta)OTEL_TRACES_EXPORTER plus CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1Distributed tracing systems for span visualization, request waterfalls and latency analysis

    A full-featured observability platform can hold all three. It earns its place when you need to correlate them, for example to jump from a cost spike in a metric to the events and spans behind it.

    Exporting takes several switches, and each one is a place for a CI rollout to go silently wrong. CLAUDE_CODE_ENABLE_TELEMETRY=1 turns collection on, but it does not choose an exporter. The metrics and logs exporters are optional, and with neither set, nothing reaches the collector. If you pick otlp, you also need a protocol, because Claude Code has no default OTLP protocol. You need an endpoint too. OTEL_EXPORTER_OTLP_HEADERS carries whatever credential your collector expects. It is not an Anthropic key. CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1 matters only for traces, because metrics and log events do not need it. The console exporter is a debugging aid, not a prerequisite.

    A settings-file env block that sends metrics and log events to a gRPC OTLP collectorjson
    {
      "env": {
        "CLAUDE_CODE_ENABLE_TELEMETRY": "1",
        "OTEL_METRICS_EXPORTER": "otlp",
        "OTEL_LOGS_EXPORTER": "otlp",
        "OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",
        "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.example.com:4317",
        "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer example-token"
      }
    }

    The Agent SDK reads the same variables. In production, set them in the process environment: every query() call picks them up with no code change. Pass them per call through ClaudeAgentOptions.env only when different agents in one process need different telemetry. That option behaves differently in the two SDKs. In Python, env is merged on top of the inherited environment. In TypeScript, it replaces the inherited environment, so spread process.env into it or you lose PATH and your API key. The default metrics interval is 60 seconds and the default logs interval is 5 seconds. Shorten both while debugging, and reset them for production.

    Checkpoint 1 of 7· Match them up

    An on-call engineer has three questions about a production agent. Match each OpenTelemetry signal to the question it answers.

    Tap a term, then the definition that fits it.

    Checkpoint 2 of 7· Fill the gap

    This settings-file env block should send both metrics and log events to a gRPC OTLP collector. Without the blanked key, log events never leave the process. Which key fills the blank?

    {
      "env": {
        "CLAUDE_CODE_ENABLE_TELEMETRY": "1",
        "OTEL_METRICS_EXPORTER": "otlp",
        " ? ": "otlp",
        "OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",
        "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.example.com:4317",
        "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer example-token"
      }
    }

    Checkpoint 3 of 7· Exam question

    A platform engineer sets CLAUDE_CODE_ENABLE_TELEMETRY=1 on every CI runner but the team's OTLP collector never receives any spans, metrics, or logs from Claude Code jobs. No other telemetry variables were configured. What is the most likely cause of the missing data?

    Sources12

    2.Controlling what metrics carry

    Metric cost in most backends depends on cardinality: every distinct combination of attribute values is its own time series. Short-lived CLI sessions make this worse, because session.id is on metric datapoints by default. A thousand CI jobs therefore produce a thousand separate series for the same counter. The fix is to remove the attribute, not to change how often you flush. Setting OTEL_METRICS_INCLUDE_SESSION_ID=false removes session.id (and ccr.session.id on cloud sessions) and leaves every other datapoint attribute alone, so the remaining breakdowns still work. A longer OTEL_METRIC_EXPORT_INTERVAL only sends the same series less often.

    Metric attribute switches and their defaults
    VariableAddsDefault
    OTEL_METRICS_INCLUDE_SESSION_IDsession.id, and ccr.session.id on cloud sessionstrue
    OTEL_METRICS_INCLUDE_ACCOUNT_UUIDuser.account_uuid and user.account_idtrue
    OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTESKeys from OTEL_RESOURCE_ATTRIBUTES on metric datapointstrue
    OTEL_METRICS_INCLUDE_VERSIONapp.versionfalse
    OTEL_METRICS_INCLUDE_ENTRYPOINTapp.entrypointfalse

    Attribution works in the other direction. In an Agent SDK service, OTEL_SERVICE_NAME (for example support-triage-agent) and OTEL_RESOURCE_ATTRIBUTES such as deployment.environment=production, enduser.id or tenant.id let you split usage per deployment or per customer. Every resource attribute is still a dimension, though, so a per-user ID carries the same cardinality cost as a session ID. Metrics export with delta temporality by default. Set OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=cumulative if your backend expects cumulative.

    Checkpoint 4 of 7· Check yourself

    A platform team's metrics backend bill has grown sharply. Each of roughly a thousand short-lived CI jobs a day shows up as its own time series for the same Claude Code token counter. The team still wants to break usage down by deployment.environment, which they set through OTEL_RESOURCE_ATTRIBUTES. Which single change cuts the series count without losing that breakdown?

    Checkpoint 5 of 7· Exam question

    A metrics backend's bill spikes because every exported time series carries a unique session.id, fragmenting cardinality across thousands of short-lived CLI sessions. The team still needs cost and token totals broken down by model. Which change addresses the cardinality problem without losing the model breakdown?

    Sources2

    3.Reading a trace: spans across a run and its subagents

    A trace turns one turn of the agent loop into a tree. The root is claude_code.interaction, which runs from the prompt arriving to the response. Under it, each call to the Claude API is a claude_code.llm_request span, and each tool invocation is a claude_code.tool span. A tool span has two children: claude_code.tool.blocked_on_user for the permission wait and claude_code.tool.execution for the work itself. That split is the first thing to check when a turn feels slow. A long wait span means a person was approving a prompt, not that the tool was slow. A subagent is a separate agent that the main session spawns, with its own model requests and tool calls, and the Agent tool is the tool call that starts one. The subagent's own llm_request and tool spans nest under that Agent tool's span.

    claude_code.llm_request attributes that locate time, tokens and the issuing agent
    AttributeWhat it tells you
    duration_ms / ttft_msWall-clock duration including retries / time to first token
    attempt, error_classTotal attempts made; a short error class such as api_timeout or server_overload
    input_tokens, output_tokensToken counts; input_tokens excludes prompt-cache reads and writes
    cache_read_tokens, cache_creation_tokensTokens read from and written to the prompt cache
    agent_id, parent_agent_idWhich subagent issued the request and which agent spawned it; both absent on the main session
    query_source_safeBounded name of the issuer, such as repl_main_thread or agent.builtin.general-purpose
    stop_reasonend_turn, tool_use, max_tokens, refusal and so on

    To find the expensive part of a multi-agent run, group llm_request spans by agent_id and sum their token attributes. Add cache_read_tokens to input_tokens when you want the full input size, because input_tokens leaves cache reads out. A high attempt count next to a long duration_ms points to retries rather than a slow model. stop_reason = max_tokens means the output was cut off. Hook spans (claude_code.hook) wrap each hook execution and appear only under detailed beta tracing (ENABLE_BETA_TRACING_DETAILED=1 plus BETA_TRACING_ENDPOINT). That mode also changes where telemetry goes: Claude Code exports logs and traces to BETA_TRACING_ENDPOINT instead of through the logs and traces exporters, so they can stop arriving at the collector you configured.

    Checkpoint 6 of 7· Check yourself

    Users say one agent turn took about 40 seconds. In the trace, the claude_code.tool span for a Bash call lasts 39 seconds. Its claude_code.tool.blocked_on_user child takes 37 seconds and its claude_code.tool.execution child takes 2 seconds. What is the most likely cause of the delay?

    Sources12

    4.Telemetry content gates: redacted by default

    By default, telemetry records the shape of the work and not its content. Prompts are reduced to their length, and the interaction span's user_prompt attribute reads <REDACTED>. Assistant responses are reduced to their length too. Tool arguments, tool output and raw file contents are left out. Each kind of content has its own gate, and the gates send data only to the endpoint you configure, never to Anthropic. That still means a collector you run will be holding source code and secrets once a gate is open. One field is present without any gate: under OAuth, user.email appears in telemetry attributes, so filter it in your backend if that matters to you.

    Content gates, from narrowest to widest
    VariableWhat it reveals
    OTEL_LOG_USER_PROMPTS=1Prompt text on user_prompt events (in both prompt and prompt_text) and on the claude_code.interaction span
    OTEL_LOG_ASSISTANT_RESPONSES=1Response text on assistant_response events; inherits OTEL_LOG_USER_PROMPTS when unset
    OTEL_LOG_TOOL_DETAILS=1Tool parameters and input: Bash commands, file paths, URLs, MCP server and tool names, skill names; real names on cost and token counters
    OTEL_LOG_TOOL_CONTENT=1A tool.output span event with file contents, Bash output and MCP/WebFetch/WebSearch results; requires tracing
    OTEL_LOG_RAW_API_BODIESFull Messages API request and response JSON, including the entire conversation history; 1 for inline, file:<dir> for untruncated bodies on disk

    Two details catch out redaction rules. First, masking prompt text in a collector has to cover both prompt and prompt_text. Second, under detailed beta tracing the llm_request span carries model output in response.model_output, and that attribute follows OTEL_LOG_USER_PROMPTS, not the responses gate. Raw API bodies are the widest gate: turning them on counts as consent to everything the prompt, tool-detail and tool-content gates would reveal. Inline content is truncated at CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH, which defaults to 61440 UTF-16 code units (60 KB) so values fit backends that cap attributes at 64 KB.

    Checkpoint 7 of 7· Match them up

    A security team will open only the content gate each audit needs, so the collector holds as little source code and as few secrets as possible. Match each gate to what it adds to telemetry.

    Tap a term, then the definition that fits it.

    Sources23

    Sources

    (3)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Counters for tokens, cost, sessions, lines of code, and tool decisions”
      ↩︎ Metrics, log events and traces answer different questions
      “In TypeScript, env replaces the inherited environment entirely, so include ...process.env in the object you pass.”
      ↩︎ Metrics, log events and traces answer different questions
      “wraps each call to the Claude API, with model name, latency, and token counts as attributes.”
      ↩︎ Reading a trace: spans across a run and its subagents
      “Metrics | Counters for tokens, cost, sessions, lines of code, and tool decisions | OTEL_METRICS_EXPORTER”
      ↩︎ Checkpoint
      “claude_code.tool: wraps each tool invocation, with child spans for the permission wait (claude_code.tool.blocked_on_user) and the execution itself (claude_code.tool.execution).”
      ↩︎ Checkpoint
    2. 2.
      “Claude Code has no default protocol, so set this or the signal-specific protocol variable for each otlp exporter you enable”
      ↩︎ Metrics, log events and traces answer different questions
      “Distributed tracing systems: Span visualization, request waterfalls, latency analysis”
      ↩︎ Metrics, log events and traces answer different questions
      “Include session.id and, on cloud sessions, ccr.session.id attributes in metrics”
      ↩︎ Controlling what metrics carry
      “Metrics temporality preference (default: delta). Set to cumulative if your backend expects cumulative temporality”
      ↩︎ Controlling what metrics carry
      “Identifier of the subagent or teammate that issued the request. Absent on the main session”
      ↩︎ Reading a trace: spans across a run and its subagents
      “(Agent tool) subagent claude_code.llm_request / claude_code.tool spans”
      ↩︎ Reading a trace: spans across a run and its subagents
      “Claude Code exports logs and traces to BETA_TRACING_ENDPOINT instead of through the logs and traces exporters”
      ↩︎ Reading a trace: spans across a run and its subagents
      “User prompt content is not collected by default. Only prompt length is recorded.”
      ↩︎ Telemetry content gates: redacted by default
      “Bodies include the entire conversation history. Enabling this implies consent to everything OTEL_LOG_USER_PROMPTS, OTEL_LOG_TOOL_DETAILS, and OTEL_LOG_TOOL_CONTENT would reveal”
      ↩︎ Telemetry content gates: redacted by default
      “Developers can’t point one signal at a different collector”
      ↩︎ Telemetry content gates: redacted by default
      “follow normal per-key precedence. A developer’s setting can still disable a signal or switch it to the console exporter”
      ↩︎ Telemetry content gates: redacted by default
      “OpenTelemetry export to your backend is opt-in and requires explicit configuration.”
      ↩︎ Key concept
      “Choose exporters (both are optional - configure only what you need)”
      ↩︎ Exam trap 1
      “Include session.id and, on cloud sessions, ccr.session.id attributes in metrics”
      ↩︎ Exam trap 2
      “When this variable is unset, OTEL_LOG_USER_PROMPTS is used as a fallback”
      ↩︎ Exam trap 3
      “OTEL_METRICS_INCLUDE_SESSION_ID | Include session.id and, on cloud sessions, ccr.session.id attributes in metrics | true”
      ↩︎ Checkpoint
      “When this variable is unset, OTEL_LOG_USER_PROMPTS is used as a fallback”
      ↩︎ Prediction
      “To include it, set OTEL_LOG_TOOL_CONTENT=1. The claude_code.tool span then carries a tool.output span event with raw file contents, Bash command output”
      ↩︎ Checkpoint
    3. 3.
      “Deploy and enforce settings across all Claude Code users to match internal policies”
      ↩︎ Telemetry content gates: redacted by default

    Continue to part 2 of 2

    Organisation-wide monitoring: API traces, usage and cost reports, audit events

    Spotted a mistake, or was something unclear? Tell us.