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.
| Signal | Enable with | Suited backends |
|---|---|---|
| Metrics | OTEL_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 events | OTEL_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=1 | Distributed 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.
{
"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.
Metrics are counters, so they suit totals and rates such as tokens and cost. Log events are one structured record per prompt, API request, API error or tool result, so they answer what happened. Traces are timed spans per interaction, model request, tool call and hook, so they show where time went.
“Metrics | Counters for tokens, cost, sessions, lines of code, and tool decisions | OTEL_METRICS_EXPORTER”Source: code.claude.com
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"
}
}Each signal needs its own exporter, and CLAUDE_CODE_ENABLE_TELEMETRY only turns collection on. OTEL_LOGS_EXPORTER is the exporter for log events. The enhanced-telemetry beta flag and OTEL_TRACES_EXPORTER apply only to traces. OTEL_LOG_USER_PROMPTS controls whether prompt text is included and does not pick an exporter.
Source: code.claude.comCheckpoint 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?
Correct answer: B — Telemetry is enabled but no exporter was selected, so OTEL_METRICS_EXPORTER and OTEL_LOGS_EXPORTER default to producing no export at all
- A. Incorrect. The enhanced telemetry beta flag is only required to unlock distributed tracing spans; metrics and log events do not depend on it, and it has no bearing on whether an exporter is configured.
- B. Correct. Enabling telemetry alone does not choose a destination. Each signal has its own exporter switch (OTEL_METRICS_EXPORTER, OTEL_LOGS_EXPORTER, OTEL_TRACES_EXPORTER), and leaving them unset means nothing is exported even though telemetry generation is on.
- C. Incorrect. The console exporter is one optional choice among several (otlp, prometheus, console, none); it is not a prerequisite the CLI requires before other exporters will function.
- D. Incorrect. OTEL_EXPORTER_OTLP_HEADERS carries authentication for the collector endpoint, not an Anthropic Admin API key, and its absence would cause auth failures at the collector, not a total absence of any emitted telemetry.
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.
| Variable | Adds | Default |
|---|---|---|
| OTEL_METRICS_INCLUDE_SESSION_ID | session.id, and ccr.session.id on cloud sessions | true |
| OTEL_METRICS_INCLUDE_ACCOUNT_UUID | user.account_uuid and user.account_id | true |
| OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES | Keys from OTEL_RESOURCE_ATTRIBUTES on metric datapoints | true |
| OTEL_METRICS_INCLUDE_VERSION | app.version | false |
| OTEL_METRICS_INCLUDE_ENTRYPOINT | app.entrypoint | false |
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?
Every CI job is a new session, and session.id is on metric datapoints by default, so each job creates its own series. Turning off OTEL_METRICS_INCLUDE_SESSION_ID removes only that attribute and keeps the resource-attribute breakdowns. A longer export interval sends the same series less often. Dropping resource attributes would lose deployment.environment. Temporality changes how values are reported, not how many series exist.
“OTEL_METRICS_INCLUDE_SESSION_ID | Include session.id and, on cloud sessions, ccr.session.id attributes in metrics | true”Source: code.claude.com
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?
Correct answer: A — Set OTEL_METRICS_INCLUDE_SESSION_ID=false so session.id is dropped from exported metrics while other attributes like model remain
- A. Correct. This variable specifically controls whether session.id is included as a metric attribute; turning it off removes the high-cardinality dimension while attributes like model, which are needed for the breakdown, are unaffected.
- B. Incorrect. This abandons real-time CLI metrics entirely and substitutes a different, higher-latency data source; it also does not solve the underlying cardinality configuration issue for teams that still want live metrics.
- C. Incorrect. A longer export interval changes how often the same set of time series is flushed, not how many distinct series are created; cardinality is driven by attribute values, not export frequency.
- D. Incorrect. The Usage and Cost Admin API is a separate, unrelated data source for billing reports; its bucket_width parameter has no effect on the CLI's own OpenTelemetry metrics pipeline or its cardinality.
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.
| Attribute | What it tells you |
|---|---|
| duration_ms / ttft_ms | Wall-clock duration including retries / time to first token |
| attempt, error_class | Total attempts made; a short error class such as api_timeout or server_overload |
| input_tokens, output_tokens | Token counts; input_tokens excludes prompt-cache reads and writes |
| cache_read_tokens, cache_creation_tokens | Tokens read from and written to the prompt cache |
| agent_id, parent_agent_id | Which subagent issued the request and which agent spawned it; both absent on the main session |
| query_source_safe | Bounded name of the issuer, such as repl_main_thread or agent.builtin.general-purpose |
| stop_reason | end_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?
blocked_on_user times the permission wait and execution times the actual work. Here 37 of the 39 seconds were spent waiting for approval, and the command ran in 2 seconds. Retries would show as a high attempt count on an llm_request span, and a cutoff would show as stop_reason = max_tokens. Neither of those would appear inside the tool span.
“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).”Source: code.claude.com
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.
| Variable | What it reveals |
|---|---|
| OTEL_LOG_USER_PROMPTS=1 | Prompt text on user_prompt events (in both prompt and prompt_text) and on the claude_code.interaction span |
| OTEL_LOG_ASSISTANT_RESPONSES=1 | Response text on assistant_response events; inherits OTEL_LOG_USER_PROMPTS when unset |
| OTEL_LOG_TOOL_DETAILS=1 | Tool 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=1 | A tool.output span event with file contents, Bash output and MCP/WebFetch/WebSearch results; requires tracing |
| OTEL_LOG_RAW_API_BODIES | Full 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.
Each kind of content has its own gate. Tool details cover what was passed to a tool, and tool content covers what the tool returned, which is recorded as a span event and so needs tracing. 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.
“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”Source: code.claude.com
Sources
(3)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 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.https://code.claude.com/docs/en/monitoring-usageOfficial docs
“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.
“Deploy and enforce settings across all Claude Code users to match internal policies”
↩︎ Telemetry content gates: redacted by default