Observability with OpenTelemetry
--- a/observability.md
+++ b/observability.md
@@ -198,7 +198,7 @@
`OTEL_LOG_USER_PROMPTS=1`| Prompt text on `claude_code.user_prompt` events and on the `claude_code.interaction` span
`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments such as file paths, shell commands, and search patterns on `claude_code.tool_result` events, and real agent, skill, plugin, and MCP server names on the [cost and token metrics](</docs/en/monitoring-usage#cost-counter>). The built-in rule the auto mode classifier named when it blocked a call, as [`classifier_category`](</docs/en/monitoring-usage#tool-decision-event>) on `claude_code.tool_decision` events
`OTEL_LOG_TOOL_CONTENT=1`| A [`tool.output` span event](</docs/en/monitoring-usage#tool-output-span-event>) on `claude_code.tool` with file contents, Bash output, and what MCP tools, WebFetch, and WebSearch return, truncated at 60 KB by default, configurable via `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`, which requires Claude Code v2.1.214 or later. Results from MCP tools, WebFetch, and WebSearch require Claude Code v2.1.283 or later. Requires tracing to be enabled. Span attributes carry tool content under [their own gates](</docs/en/monitoring-usage#new-context-gates>)
-`OTEL_LOG_RAW_API_BODIES`| Full Anthropic Messages API request and response JSON as `claude_code.api_request_body` and `claude_code.api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB by default, or `file:<dir>` for untruncated bodies on disk with a `body_ref` path in the event. `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH` configures the inline truncation limit, and requires Claude Code v2.1.214 or later. Bodies include the entire conversation history and have extended-thinking content redacted. Enabling this implies consent to everything the three variables above would reveal
+`OTEL_LOG_RAW_API_BODIES`| Full Anthropic Messages API request and response JSON as `claude_code.api_request_body` and `claude_code.api_response_body` log events. Set to `1` for inline bodies truncated at [60 KB by default](</docs/en/monitoring-usage#common-configuration-variables>), or `file:<dir>` for untruncated bodies on disk with a `body_ref` path in the event. Bodies can include the entire conversation history, with extended-thinking content redacted. Enabling this implies consent to everything the three variables above would reveal
Leave these unset unless your observability pipeline is approved to store the data your agent handles. See [Security and privacy](</docs/en/monitoring-usage#security-and-privacy>) in the Monitoring reference for the full list of attributes and redaction behavior.
Show diff (115 lines)
--- a/observability.md
+++ b/observability.md
@@ -9,11 +9,7 @@
For the Claude API or Managed Agents, see [OpenTelemetry for the Claude API](<https://platform.claude.com/docs/en/manage-claude/opentelemetry>).
-##
-
-
-
-How telemetry flows from the SDK
+## How telemetry flows from the SDK
The Agent SDK runs the Claude Code CLI as a child process and communicates with it over a local pipe. The CLI has OpenTelemetry instrumentation built in: it records spans around each model request and tool execution, emits metrics for token and cost counters, and emits structured log events for prompts and tool results. The SDK does not produce telemetry of its own. Instead, it passes configuration through to the CLI process, and the CLI exports directly to your collector. Configuration is passed as environment variables. By default, the child process inherits your application’s environment, so you can configure telemetry in either of two places:
@@ -30,11 +26,7 @@
For the complete list of metric names, event names, and attributes, see the Claude Code [Monitoring](</docs/en/monitoring-usage>) reference. The Agent SDK emits the same data because it runs the same CLI. Span names are listed in Read agent traces below.
-##
-
-
-
-Enable telemetry export
+## Enable telemetry export
Telemetry is off until you set `CLAUDE_CODE_ENABLE_TELEMETRY=1` and choose at least one exporter. The most common configuration sends all three signals over OTLP HTTP to a collector. The following example sets the variables in a dictionary and passes them through `options.env`. The agent runs a single task, and the CLI exports spans, metrics, and events to the collector at `collector.example.com` while the loop consumes the response stream:
@@ -97,11 +89,7 @@
The `console` exporter writes telemetry to standard output, which the SDK uses as its message channel. Do not set `console` as an exporter value when running through the SDK. To inspect telemetry locally, point `OTEL_EXPORTER_OTLP_ENDPOINT` at a local OpenTelemetry Collector instead.
-###
-
-
-
-Flush telemetry from short-lived calls
+### Flush telemetry from short-lived calls
The CLI batches telemetry and exports on an interval. On a clean process exit it attempts to flush pending data, but the flush is bounded by a short timeout, so spans can still be dropped if the collector is slow to respond. If your process is killed before the CLI shuts down, anything still in the batch buffer is lost. Lowering the export intervals reduces both windows. By default, metrics export every 60 seconds and traces and logs export every 5 seconds. The following example shortens all three intervals so that data reaches the collector while a short task is still running:
@@ -123,11 +111,7 @@
OTEL_TRACES_EXPORT_INTERVAL: "1000",
};
-##
-
-
-
-Read agent traces
+## Read agent traces
Traces give you the most detailed view of an agent run. With `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1` set, each step of the agent loop becomes a span you can inspect in your tracing backend:
@@ -140,19 +124,11 @@
Tracing is in beta. Span names and attributes may change between releases. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the trace exporter configuration variables.
-##
-
-
-
-Link traces to your application
+## Link traces to your application
The SDK automatically propagates W3C trace context into the CLI subprocess. When you call `query()` while an OpenTelemetry span is active in your application, the SDK injects `TRACEPARENT` and `TRACESTATE` into the child process environment, and the CLI reads them so its `claude_code.interaction` span becomes a child of your span. The agent run then appears inside your application’s trace instead of as a disconnected root. OTLP event log records emitted during the run carry the same trace context: with `TRACEPARENT` set, each record’s `trace_id` and `span_id` match your application’s trace, so you can join [events](</docs/en/monitoring-usage#events>) to spans in your backend. Before v2.1.212, event records emitted outside an active span didn’t carry `trace_id` or `span_id`. When trace-context propagation is enabled, the CLI also forwards `TRACEPARENT` to every Bash and PowerShell command it runs. If a command launched through the Bash tool emits its own OpenTelemetry spans, those spans nest under the `claude_code.tool.execution` span that wraps the command. Auto-injection is skipped when you set `TRACEPARENT` explicitly in `options.env`, so you can pin a specific parent context if needed. Interactive CLI sessions ignore inbound `TRACEPARENT` entirely; only Agent SDK and `claude -p` runs honor it. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the full span and attribute reference.
-##
-
-
-
-Tag telemetry from your agent
+## Tag telemetry from your agent
By default, the CLI reports `service.name` as `claude-code`. If you run several agents, or run the SDK alongside other services that export to the same collector, override the service name and add resource attributes so you can filter by agent in your backend. The following example renames the service and attaches deployment metadata. These values are applied as OpenTelemetry resource attributes on every span, metric, and event the agent emits:
@@ -178,11 +154,7 @@
},
};
-##
-
-
-
-Attribute actions to your end users
+## Attribute actions to your end users
The CLI attaches [identity attributes](</docs/en/monitoring-usage#standard-attributes>) to every event based on the credential it uses to call Anthropic. When you build an application that serves many end users from one deployment, these attributes identify your service’s credential, not the end user on whose behalf the agent acted. To make tool calls and MCP activity attributable to your application’s end users, inject end-user identity as resource attributes on each `query()` call. Percent-encode values before interpolating them, since `OTEL_RESOURCE_ATTRIBUTES` [reserves commas, spaces, and equals signs](</docs/en/monitoring-usage#multi-team-organization-support>). The following example attaches the requesting user and tenant to every span and event from one request. It assumes a `request` object from your web framework carrying the user and tenant IDs:
@@ -217,11 +189,7 @@
These events export as log records named with a `claude_code.` prefix, such as `claude_code.tool_decision`. See [Audit security events](</docs/en/monitoring-usage#audit-security-events>) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries.
-##
-
-
-
-Control sensitive data in exports
+## Control sensitive data in exports
Telemetry is structural by default. Durations, model names, and tool names are recorded on every span; token counts are recorded when the underlying API request returns usage data, so spans for failed or aborted requests may omit them. The content your agent reads and writes is not recorded by default. These opt-in variables add content to the exported data:
@@ -234,11 +202,7 @@
Leave these unset unless your observability pipeline is approved to store the data your agent handles. See [Security and privacy](</docs/en/monitoring-usage#security-and-privacy>) in the Monitoring reference for the full list of attributes and redaction behavior.
-##
-
-
-
-Related documentation
+## Related documentation
These guides cover adjacent topics for monitoring and deploying agents:
--- a/observability.md
+++ b/observability.md
@@ -212,11 +212,10 @@
After you attach end-user identity, these events become a per-user audit trail you can forward to a Security Information and Event Management (SIEM) platform:
* `tool_decision` and `tool_result`: each tool call, whether it was allowed or denied, and its result
- * `safety_event`: which check refused a tool call or required a permission prompt for it, such as a permission rule or the auto mode classifier. Some calls [have no safety event](</docs/en/monitoring-usage#calls-without-a-safety-event>). Requires Claude Code v2.1.307 or later
* `mcp_server_connection`: MCP server connections and connection failures
* `permission_mode_changed`: permission mode changes
-These events export as log records named with a `claude_code.` prefix, such as `claude_code.safety_event`. See [Audit security events](</docs/en/monitoring-usage#audit-security-events>) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries.
+These events export as log records named with a `claude_code.` prefix, such as `claude_code.tool_decision`. See [Audit security events](</docs/en/monitoring-usage#audit-security-events>) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries.
##
@@ -229,7 +228,7 @@
Variable| Adds
---|---
`OTEL_LOG_USER_PROMPTS=1`| Prompt text on `claude_code.user_prompt` events and on the `claude_code.interaction` span
-`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments such as file paths, shell commands, and search patterns on `claude_code.tool_result` events, and real agent, skill, plugin, and MCP server names on the [cost and token metrics](</docs/en/monitoring-usage#cost-counter>). The built-in rule the auto mode classifier named when it blocked a call, as [`classifier_category`](</docs/en/monitoring-usage#tool-decision-event>) on `claude_code.tool_decision` and `claude_code.safety_event` events
+`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments such as file paths, shell commands, and search patterns on `claude_code.tool_result` events, and real agent, skill, plugin, and MCP server names on the [cost and token metrics](</docs/en/monitoring-usage#cost-counter>). The built-in rule the auto mode classifier named when it blocked a call, as [`classifier_category`](</docs/en/monitoring-usage#tool-decision-event>) on `claude_code.tool_decision` events
`OTEL_LOG_TOOL_CONTENT=1`| A [`tool.output` span event](</docs/en/monitoring-usage#tool-output-span-event>) on `claude_code.tool` with file contents, Bash output, and what MCP tools, WebFetch, and WebSearch return, truncated at 60 KB by default, configurable via `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`, which requires Claude Code v2.1.214 or later. Results from MCP tools, WebFetch, and WebSearch require Claude Code v2.1.283 or later. Requires tracing to be enabled. Span attributes carry tool content under [their own gates](</docs/en/monitoring-usage#new-context-gates>)
`OTEL_LOG_RAW_API_BODIES`| Full Anthropic Messages API request and response JSON as `claude_code.api_request_body` and `claude_code.api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB by default, or `file:<dir>` for untruncated bodies on disk with a `body_ref` path in the event. `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH` configures the inline truncation limit, and requires Claude Code v2.1.214 or later. Bodies include the entire conversation history and have extended-thinking content redacted. Enabling this implies consent to everything the three variables above would reveal
--- a/observability.md
+++ b/observability.md
@@ -209,7 +209,14 @@
},
};
-With end-user identity attached, the `tool_decision`, `tool_result`, `mcp_server_connection`, and `permission_mode_changed` events, which export as log records named with a `claude_code.` prefix, become a per-user audit trail you can forward to a Security Information and Event Management (SIEM) platform. See [Audit security events](</docs/en/monitoring-usage#audit-security-events>) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries.
+After you attach end-user identity, these events become a per-user audit trail you can forward to a Security Information and Event Management (SIEM) platform:
+
+ * `tool_decision` and `tool_result`: each tool call, whether it was allowed or denied, and its result
+ * `safety_event`: which check refused a tool call or required a permission prompt for it, such as a permission rule or the auto mode classifier. Some calls [have no safety event](</docs/en/monitoring-usage#calls-without-a-safety-event>). Requires Claude Code v2.1.307 or later
+ * `mcp_server_connection`: MCP server connections and connection failures
+ * `permission_mode_changed`: permission mode changes
+
+These events export as log records named with a `claude_code.` prefix, such as `claude_code.safety_event`. See [Audit security events](</docs/en/monitoring-usage#audit-security-events>) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries.
##
@@ -222,7 +229,7 @@
Variable| Adds
---|---
`OTEL_LOG_USER_PROMPTS=1`| Prompt text on `claude_code.user_prompt` events and on the `claude_code.interaction` span
-`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments such as file paths, shell commands, and search patterns on `claude_code.tool_result` events, and real agent, skill, plugin, and MCP server names on the [cost and token metrics](</docs/en/monitoring-usage#cost-counter>)
+`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments such as file paths, shell commands, and search patterns on `claude_code.tool_result` events, and real agent, skill, plugin, and MCP server names on the [cost and token metrics](</docs/en/monitoring-usage#cost-counter>). The built-in rule the auto mode classifier named when it blocked a call, as [`classifier_category`](</docs/en/monitoring-usage#tool-decision-event>) on `claude_code.tool_decision` and `claude_code.safety_event` events
`OTEL_LOG_TOOL_CONTENT=1`| A [`tool.output` span event](</docs/en/monitoring-usage#tool-output-span-event>) on `claude_code.tool` with file contents, Bash output, and what MCP tools, WebFetch, and WebSearch return, truncated at 60 KB by default, configurable via `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`, which requires Claude Code v2.1.214 or later. Results from MCP tools, WebFetch, and WebSearch require Claude Code v2.1.283 or later. Requires tracing to be enabled. Span attributes carry tool content under [their own gates](</docs/en/monitoring-usage#new-context-gates>)
`OTEL_LOG_RAW_API_BODIES`| Full Anthropic Messages API request and response JSON as `claude_code.api_request_body` and `claude_code.api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB by default, or `file:<dir>` for untruncated bodies on disk with a `body_ref` path in the event. `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH` configures the inline truncation limit, and requires Claude Code v2.1.214 or later. Bodies include the entire conversation history and have extended-thinking content redacted. Enabling this implies consent to everything the three variables above would reveal
--- a/observability.md
+++ b/observability.md
@@ -6,6 +6,8 @@
* where failures occurred
The Agent SDK can export this data as OpenTelemetry traces, metrics, and log events to any backend that accepts the OpenTelemetry Protocol (OTLP), whether a hosted observability platform or a self-hosted collector. This guide explains how the SDK emits telemetry, how to configure the export, and how to tag and filter the data once it reaches your backend. To read token usage and cost directly from the SDK response stream instead of exporting to a backend, see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>).
+
+For the Claude API or Managed Agents, see [OpenTelemetry for the Claude API](<https://platform.claude.com/docs/en/manage-claude/opentelemetry>).
##
--- a/observability.md
+++ b/observability.md
@@ -220,7 +220,7 @@
Variable| Adds
---|---
`OTEL_LOG_USER_PROMPTS=1`| Prompt text on `claude_code.user_prompt` events and on the `claude_code.interaction` span
-`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments (file paths, shell commands, search patterns) on `claude_code.tool_result` events
+`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments such as file paths, shell commands, and search patterns on `claude_code.tool_result` events, and real agent, skill, plugin, and MCP server names on the [cost and token metrics](</docs/en/monitoring-usage#cost-counter>)
`OTEL_LOG_TOOL_CONTENT=1`| A [`tool.output` span event](</docs/en/monitoring-usage#tool-output-span-event>) on `claude_code.tool` with file contents, Bash output, and what MCP tools, WebFetch, and WebSearch return, truncated at 60 KB by default, configurable via `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`, which requires Claude Code v2.1.214 or later. Results from MCP tools, WebFetch, and WebSearch require Claude Code v2.1.283 or later. Requires tracing to be enabled. Span attributes carry tool content under [their own gates](</docs/en/monitoring-usage#new-context-gates>)
`OTEL_LOG_RAW_API_BODIES`| Full Anthropic Messages API request and response JSON as `claude_code.api_request_body` and `claude_code.api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB by default, or `file:<dir>` for untruncated bodies on disk with a `body_ref` path in the event. `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH` configures the inline truncation limit, and requires Claude Code v2.1.214 or later. Bodies include the entire conversation history and have extended-thinking content redacted. Enabling this implies consent to everything the three variables above would reveal
--- a/observability.md
+++ b/observability.md
@@ -221,7 +221,7 @@
---|---
`OTEL_LOG_USER_PROMPTS=1`| Prompt text on `claude_code.user_prompt` events and on the `claude_code.interaction` span
`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments (file paths, shell commands, search patterns) on `claude_code.tool_result` events
-`OTEL_LOG_TOOL_CONTENT=1`| A [`tool.output` span event](</docs/en/monitoring-usage#tool-output-span-event>) on `claude_code.tool` with file contents and Bash output, truncated at 60 KB by default, configurable via `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`, which requires Claude Code v2.1.214 or later. Requires tracing to be enabled. Span attributes carry tool content under [their own gates](</docs/en/monitoring-usage#new-context-gates>)
+`OTEL_LOG_TOOL_CONTENT=1`| A [`tool.output` span event](</docs/en/monitoring-usage#tool-output-span-event>) on `claude_code.tool` with file contents, Bash output, and what MCP tools, WebFetch, and WebSearch return, truncated at 60 KB by default, configurable via `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`, which requires Claude Code v2.1.214 or later. Results from MCP tools, WebFetch, and WebSearch require Claude Code v2.1.283 or later. Requires tracing to be enabled. Span attributes carry tool content under [their own gates](</docs/en/monitoring-usage#new-context-gates>)
`OTEL_LOG_RAW_API_BODIES`| Full Anthropic Messages API request and response JSON as `claude_code.api_request_body` and `claude_code.api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB by default, or `file:<dir>` for untruncated bodies on disk with a `body_ref` path in the event. `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH` configures the inline truncation limit, and requires Claude Code v2.1.214 or later. Bodies include the entire conversation history and have extended-thinking content redacted. Enabling this implies consent to everything the three variables above would reveal
Leave these unset unless your observability pipeline is approved to store the data your agent handles. See [Security and privacy](</docs/en/monitoring-usage#security-and-privacy>) in the Monitoring reference for the full list of attributes and redaction behavior.
--- a/observability.md
+++ b/observability.md
@@ -221,7 +221,7 @@
---|---
`OTEL_LOG_USER_PROMPTS=1`| Prompt text on `claude_code.user_prompt` events and on the `claude_code.interaction` span
`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments (file paths, shell commands, search patterns) on `claude_code.tool_result` events
-`OTEL_LOG_TOOL_CONTENT=1`| Full tool input and output bodies as span events on `claude_code.tool`, truncated at 60 KB by default, configurable via `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`, which requires Claude Code v2.1.214 or later. Requires tracing to be enabled
+`OTEL_LOG_TOOL_CONTENT=1`| A [`tool.output` span event](</docs/en/monitoring-usage#tool-output-span-event>) on `claude_code.tool` with file contents and Bash output, truncated at 60 KB by default, configurable via `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`, which requires Claude Code v2.1.214 or later. Requires tracing to be enabled. Span attributes carry tool content under [their own gates](</docs/en/monitoring-usage#new-context-gates>)
`OTEL_LOG_RAW_API_BODIES`| Full Anthropic Messages API request and response JSON as `claude_code.api_request_body` and `claude_code.api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB by default, or `file:<dir>` for untruncated bodies on disk with a `body_ref` path in the event. `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH` configures the inline truncation limit, and requires Claude Code v2.1.214 or later. Bodies include the entire conversation history and have extended-thinking content redacted. Enabling this implies consent to everything the three variables above would reveal
Leave these unset unless your observability pipeline is approved to store the data your agent handles. See [Security and privacy](</docs/en/monitoring-usage#security-and-privacy>) in the Monitoring reference for the full list of attributes and redaction behavior.
--- a/observability.md
+++ b/observability.md
@@ -132,7 +132,7 @@
* **`claude_code.interaction`:** wraps a single turn of the agent loop, from receiving a prompt to producing a response.
* **`claude_code.llm_request`:** wraps each call to the Claude API, with model name, latency, and token counts as attributes.
* **`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`).
- * **`claude_code.hook`:** wraps each [hook](</docs/en/agent-sdk/hooks>) execution. Requires detailed beta tracing (`ENABLE_BETA_TRACING_DETAILED=1` and `BETA_TRACING_ENDPOINT`) in addition to the variables above.
+ * **`claude_code.hook`:** wraps each [hook](</docs/en/agent-sdk/hooks>) execution. Requires detailed beta tracing (`ENABLE_BETA_TRACING_DETAILED=1` and `BETA_TRACING_ENDPOINT`), a pair that also [changes where your logs and traces go](</docs/en/env-vars#variables>).
The `llm_request`, `tool`, and `hook` spans are children of the enclosing `claude_code.interaction` span. When the agent spawns a subagent through the Agent tool, the subagent’s `llm_request` and `tool` spans nest under the parent agent’s `claude_code.tool` span, so the full delegation chain appears as one trace. Spans carry a `session.id` attribute by default. When you make several `query()` calls against the same [session](</docs/en/agent-sdk/sessions>), filter on `session.id` in your backend to see them as one timeline. Claude Code omits the attribute if you set `OTEL_METRICS_INCLUDE_SESSION_ID` to a falsy value.
--- a/observability.md
+++ b/observability.md
@@ -5,7 +5,7 @@
* how many tokens were spent
* where failures occurred
-The Agent SDK can export this data as OpenTelemetry traces, metrics, and log events to any backend that accepts the OpenTelemetry Protocol (OTLP), such as Honeycomb, Datadog, Grafana, Langfuse, or a self-hosted collector. This guide explains how the SDK emits telemetry, how to configure the export, and how to tag and filter the data once it reaches your backend. To read token usage and cost directly from the SDK response stream instead of exporting to a backend, see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>).
+The Agent SDK can export this data as OpenTelemetry traces, metrics, and log events to any backend that accepts the OpenTelemetry Protocol (OTLP), whether a hosted observability platform or a self-hosted collector. This guide explains how the SDK emits telemetry, how to configure the export, and how to tag and filter the data once it reaches your backend. To read token usage and cost directly from the SDK response stream instead of exporting to a backend, see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>).
##
@@ -93,7 +93,7 @@
Because the child process inherits your application’s environment by default, you can achieve the same result by exporting these variables in a Dockerfile, Kubernetes manifest, or shell profile and omitting `options.env` entirely. To confirm that export is working, check your collector’s logs for incoming spans, metrics, and log events after the task completes. The CLI fails silently on export errors by default: if the endpoint is unreachable or rejects the data, the agent still runs normally and the CLI drops the telemetry without surfacing an error in your application. To surface exporter errors, set [`CLAUDE_CODE_OTEL_DIAG_STDERR=1`](</docs/en/env-vars>) alongside the exporter variables and read the diagnostics through the SDK’s `stderr` callback (Python) or `stderr` option (TypeScript). Requires Claude Code v2.1.179 or later.
-The `console` exporter writes telemetry to standard output, which the SDK uses as its message channel. Do not set `console` as an exporter value when running through the SDK. To inspect telemetry locally, point `OTEL_EXPORTER_OTLP_ENDPOINT` at a local collector or an all-in-one Jaeger container instead.
+The `console` exporter writes telemetry to standard output, which the SDK uses as its message channel. Do not set `console` as an exporter value when running through the SDK. To inspect telemetry locally, point `OTEL_EXPORTER_OTLP_ENDPOINT` at a local OpenTelemetry Collector instead.
###
--- a/observability.md
+++ b/observability.md
@@ -134,7 +134,7 @@
* **`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`).
* **`claude_code.hook`:** wraps each [hook](</docs/en/agent-sdk/hooks>) execution. Requires detailed beta tracing (`ENABLE_BETA_TRACING_DETAILED=1` and `BETA_TRACING_ENDPOINT`) in addition to the variables above.
-The `llm_request`, `tool`, and `hook` spans are children of the enclosing `claude_code.interaction` span. When the agent spawns a subagent through the Task tool, the subagent’s `llm_request` and `tool` spans nest under the parent agent’s `claude_code.tool` span, so the full delegation chain appears as one trace. Spans carry a `session.id` attribute by default. When you make several `query()` calls against the same [session](</docs/en/agent-sdk/sessions>), filter on `session.id` in your backend to see them as one timeline. Claude Code omits the attribute if you set `OTEL_METRICS_INCLUDE_SESSION_ID` to a falsy value.
+The `llm_request`, `tool`, and `hook` spans are children of the enclosing `claude_code.interaction` span. When the agent spawns a subagent through the Agent tool, the subagent’s `llm_request` and `tool` spans nest under the parent agent’s `claude_code.tool` span, so the full delegation chain appears as one trace. Spans carry a `session.id` attribute by default. When you make several `query()` calls against the same [session](</docs/en/agent-sdk/sessions>), filter on `session.id` in your backend to see them as one timeline. Claude Code omits the attribute if you set `OTEL_METRICS_INCLUDE_SESSION_ID` to a falsy value.
Tracing is in beta. Span names and attributes may change between releases. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the trace exporter configuration variables.
--- a/observability.md
+++ b/observability.md
@@ -134,7 +134,7 @@
* **`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`).
* **`claude_code.hook`:** wraps each [hook](</docs/en/agent-sdk/hooks>) execution. Requires detailed beta tracing (`ENABLE_BETA_TRACING_DETAILED=1` and `BETA_TRACING_ENDPOINT`) in addition to the variables above.
-The `llm_request`, `tool`, and `hook` spans are children of the enclosing `claude_code.interaction` span. When the agent spawns a subagent through the Task tool, the subagent’s `llm_request` and `tool` spans nest under the parent agent’s `claude_code.tool` span, so the full delegation chain appears as one trace. Spans carry a `session.id` attribute by default. When you make several `query()` calls against the same [session](</docs/en/agent-sdk/sessions>), filter on `session.id` in your backend to see them as one timeline. The attribute is omitted if `OTEL_METRICS_INCLUDE_SESSION_ID` is set to a falsy value.
+The `llm_request`, `tool`, and `hook` spans are children of the enclosing `claude_code.interaction` span. When the agent spawns a subagent through the Task tool, the subagent’s `llm_request` and `tool` spans nest under the parent agent’s `claude_code.tool` span, so the full delegation chain appears as one trace. Spans carry a `session.id` attribute by default. When you make several `query()` calls against the same [session](</docs/en/agent-sdk/sessions>), filter on `session.id` in your backend to see them as one timeline. Claude Code omits the attribute if you set `OTEL_METRICS_INCLUDE_SESSION_ID` to a falsy value.
Tracing is in beta. Span names and attributes may change between releases. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the trace exporter configuration variables.
--- a/observability.md
+++ b/observability.md
@@ -91,7 +91,7 @@
console.log(message);
}
-Because the child process inherits your application’s environment by default, you can achieve the same result by exporting these variables in a Dockerfile, Kubernetes manifest, or shell profile and omitting `options.env` entirely.
+Because the child process inherits your application’s environment by default, you can achieve the same result by exporting these variables in a Dockerfile, Kubernetes manifest, or shell profile and omitting `options.env` entirely. To confirm that export is working, check your collector’s logs for incoming spans, metrics, and log events after the task completes. The CLI fails silently on export errors by default: if the endpoint is unreachable or rejects the data, the agent still runs normally and the CLI drops the telemetry without surfacing an error in your application. To surface exporter errors, set [`CLAUDE_CODE_OTEL_DIAG_STDERR=1`](</docs/en/env-vars>) alongside the exporter variables and read the diagnostics through the SDK’s `stderr` callback (Python) or `stderr` option (TypeScript). Requires Claude Code v2.1.179 or later.
The `console` exporter writes telemetry to standard output, which the SDK uses as its message channel. Do not set `console` as an exporter value when running through the SDK. To inspect telemetry locally, point `OTEL_EXPORTER_OTLP_ENDPOINT` at a local collector or an all-in-one Jaeger container instead.
@@ -160,7 +160,7 @@
options = ClaudeAgentOptions(
env={
- # ... exporter configuration ...
+ # ... exporter configuration from the Enable telemetry export example ...
"OTEL_SERVICE_NAME": "support-triage-agent",
"OTEL_RESOURCE_ATTRIBUTES": "service.version=1.4.0,deployment.environment=production",
},
@@ -169,7 +169,7 @@
const options = {
env: {
...process.env,
- // ... exporter configuration ...
+ // ... exporter configuration from the Enable telemetry export example ...
OTEL_SERVICE_NAME: "support-triage-agent",
OTEL_RESOURCE_ATTRIBUTES:
"service.version=1.4.0,deployment.environment=production",
@@ -192,7 +192,8 @@
options = ClaudeAgentOptions(
env={
- # ... exporter configuration ...
+ # ... exporter configuration from the Enable telemetry export example ...
+ # request is the incoming request object from your web framework.
"OTEL_RESOURCE_ATTRIBUTES": f"enduser.id={quote(request.user_id)},tenant.id={quote(request.tenant_id)}",
},
)
@@ -200,7 +201,8 @@
const options = {
env: {
...process.env,
- // ... exporter configuration ...
+ // ... exporter configuration from the Enable telemetry export example ...
+ // request is the incoming request object from your web framework.
OTEL_RESOURCE_ATTRIBUTES: `enduser.id=${encodeURIComponent(request.userId)},tenant.id=${encodeURIComponent(request.tenantId)}`,
},
};
--- a/observability.md
+++ b/observability.md
@@ -219,8 +219,8 @@
---|---
`OTEL_LOG_USER_PROMPTS=1`| Prompt text on `claude_code.user_prompt` events and on the `claude_code.interaction` span
`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments (file paths, shell commands, search patterns) on `claude_code.tool_result` events
-`OTEL_LOG_TOOL_CONTENT=1`| Full tool input and output bodies as span events on `claude_code.tool`, truncated at 60 KB. Requires tracing to be enabled
-`OTEL_LOG_RAW_API_BODIES`| Full Anthropic Messages API request and response JSON as `claude_code.api_request_body` and `claude_code.api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB, or `file:<dir>` for untruncated bodies on disk with a `body_ref` path in the event. Bodies include the entire conversation history and have extended-thinking content redacted. Enabling this implies consent to everything the three variables above would reveal
+`OTEL_LOG_TOOL_CONTENT=1`| Full tool input and output bodies as span events on `claude_code.tool`, truncated at 60 KB by default, configurable via `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`, which requires Claude Code v2.1.214 or later. Requires tracing to be enabled
+`OTEL_LOG_RAW_API_BODIES`| Full Anthropic Messages API request and response JSON as `claude_code.api_request_body` and `claude_code.api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB by default, or `file:<dir>` for untruncated bodies on disk with a `body_ref` path in the event. `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH` configures the inline truncation limit, and requires Claude Code v2.1.214 or later. Bodies include the entire conversation history and have extended-thinking content redacted. Enabling this implies consent to everything the three variables above would reveal
Leave these unset unless your observability pipeline is approved to store the data your agent handles. See [Security and privacy](</docs/en/monitoring-usage#security-and-privacy>) in the Monitoring reference for the full list of attributes and redaction behavior.
--- a/observability.md
+++ b/observability.md
@@ -144,7 +144,7 @@
Link traces to your application
-The SDK automatically propagates W3C trace context into the CLI subprocess. When you call `query()` while an OpenTelemetry span is active in your application, the SDK injects `TRACEPARENT` and `TRACESTATE` into the child process environment, and the CLI reads them so its `claude_code.interaction` span becomes a child of your span. The agent run then appears inside your application’s trace instead of as a disconnected root. When trace-context propagation is enabled, the CLI also forwards `TRACEPARENT` to every Bash and PowerShell command it runs. If a command launched through the Bash tool emits its own OpenTelemetry spans, those spans nest under the `claude_code.tool.execution` span that wraps the command. Auto-injection is skipped when you set `TRACEPARENT` explicitly in `options.env`, so you can pin a specific parent context if needed. Interactive CLI sessions ignore inbound `TRACEPARENT` entirely; only Agent SDK and `claude -p` runs honor it. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the full span and attribute reference.
+The SDK automatically propagates W3C trace context into the CLI subprocess. When you call `query()` while an OpenTelemetry span is active in your application, the SDK injects `TRACEPARENT` and `TRACESTATE` into the child process environment, and the CLI reads them so its `claude_code.interaction` span becomes a child of your span. The agent run then appears inside your application’s trace instead of as a disconnected root. OTLP event log records emitted during the run carry the same trace context: with `TRACEPARENT` set, each record’s `trace_id` and `span_id` match your application’s trace, so you can join [events](</docs/en/monitoring-usage#events>) to spans in your backend. Before v2.1.212, event records emitted outside an active span didn’t carry `trace_id` or `span_id`. When trace-context propagation is enabled, the CLI also forwards `TRACEPARENT` to every Bash and PowerShell command it runs. If a command launched through the Bash tool emits its own OpenTelemetry spans, those spans nest under the `claude_code.tool.execution` span that wraps the command. Auto-injection is skipped when you set `TRACEPARENT` explicitly in `options.env`, so you can pin a specific parent context if needed. Interactive CLI sessions ignore inbound `TRACEPARENT` entirely; only Agent SDK and `claude -p` runs honor it. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the full span and attribute reference.
##
--- a/observability.md
+++ b/observability.md
@@ -66,6 +66,31 @@
asyncio.run(main())
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ const otelEnv = {
+ CLAUDE_CODE_ENABLE_TELEMETRY: "1",
+ // Required for traces, which are in beta. Metrics and log events do not need this.
+ CLAUDE_CODE_ENHANCED_TELEMETRY_BETA: "1",
+ // Choose an exporter per signal. Use otlp for the SDK; see the Note below.
+ OTEL_TRACES_EXPORTER: "otlp",
+ OTEL_METRICS_EXPORTER: "otlp",
+ OTEL_LOGS_EXPORTER: "otlp",
+ // Standard OTLP transport configuration.
+ OTEL_EXPORTER_OTLP_PROTOCOL: "http/protobuf",
+ OTEL_EXPORTER_OTLP_ENDPOINT: "http://collector.example.com:4318",
+ OTEL_EXPORTER_OTLP_HEADERS: "Authorization=Bearer your-token",
+ };
+
+ for await (const message of query({
+ prompt: "List the files in this directory",
+ // env replaces the inherited environment in TypeScript, so spread
+ // process.env first to keep PATH, ANTHROPIC_API_KEY, and other variables.
+ options: { env: { ...process.env, ...otelEnv } },
+ })) {
+ console.log(message);
+ }
+
Because the child process inherits your application’s environment by default, you can achieve the same result by exporting these variables in a Dockerfile, Kubernetes manifest, or shell profile and omitting `options.env` entirely.
The `console` exporter writes telemetry to standard output, which the SDK uses as its message channel. Do not set `console` as an exporter value when running through the SDK. To inspect telemetry locally, point `OTEL_EXPORTER_OTLP_ENDPOINT` at a local collector or an all-in-one Jaeger container instead.
@@ -88,6 +113,13 @@
"OTEL_LOGS_EXPORT_INTERVAL": "1000",
"OTEL_TRACES_EXPORT_INTERVAL": "1000",
}
+
+ const otelEnv = {
+ // ... exporter configuration from the previous example ...
+ OTEL_METRIC_EXPORT_INTERVAL: "1000",
+ OTEL_LOGS_EXPORT_INTERVAL: "1000",
+ OTEL_TRACES_EXPORT_INTERVAL: "1000",
+ };
##
@@ -134,6 +166,16 @@
},
)
+ const options = {
+ env: {
+ ...process.env,
+ // ... exporter configuration ...
+ OTEL_SERVICE_NAME: "support-triage-agent",
+ OTEL_RESOURCE_ATTRIBUTES:
+ "service.version=1.4.0,deployment.environment=production",
+ },
+ };
+
##
@@ -155,6 +197,14 @@
},
)
+ const options = {
+ env: {
+ ...process.env,
+ // ... exporter configuration ...
+ OTEL_RESOURCE_ATTRIBUTES: `enduser.id=${encodeURIComponent(request.userId)},tenant.id=${encodeURIComponent(request.tenantId)}`,
+ },
+ };
+
With end-user identity attached, the `tool_decision`, `tool_result`, `mcp_server_connection`, and `permission_mode_changed` events, which export as log records named with a `claude_code.` prefix, become a per-user audit trail you can forward to a Security Information and Event Management (SIEM) platform. See [Audit security events](</docs/en/monitoring-usage#audit-security-events>) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries.
##
--- a/observability.md
+++ b/observability.md
@@ -140,7 +140,7 @@
Attribute actions to your end users
-The CLI attaches [identity attributes](</docs/en/monitoring-usage#standard-attributes>) to every event based on the credential it uses to call Anthropic. When you build an application that serves many end users from one deployment, these attributes identify your service’s credential, not the end user on whose behalf the agent acted. To make tool calls and MCP activity attributable to your application’s end users, inject end-user identity as resource attributes on each `query()` call. Percent-encode values before interpolating them, since `OTEL_RESOURCE_ATTRIBUTES` [reserves commas, spaces, and equals signs](</docs/en/monitoring-usage#multi-team-organization-support>). The following example attaches the requesting user and tenant to every span and event from one request:
+The CLI attaches [identity attributes](</docs/en/monitoring-usage#standard-attributes>) to every event based on the credential it uses to call Anthropic. When you build an application that serves many end users from one deployment, these attributes identify your service’s credential, not the end user on whose behalf the agent acted. To make tool calls and MCP activity attributable to your application’s end users, inject end-user identity as resource attributes on each `query()` call. Percent-encode values before interpolating them, since `OTEL_RESOURCE_ATTRIBUTES` [reserves commas, spaces, and equals signs](</docs/en/monitoring-usage#multi-team-organization-support>). The following example attaches the requesting user and tenant to every span and event from one request. It assumes a `request` object from your web framework carrying the user and tenant IDs:
Python
@@ -155,7 +155,7 @@
},
)
-With end-user identity attached, the `tool_decision`, `tool_result`, `mcp_server_connection`, and `permission_mode_changed` events become a per-user audit trail you can forward to a Security Information and Event Management (SIEM) platform. See [Audit security events](</docs/en/monitoring-usage#audit-security-events>) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries.
+With end-user identity attached, the `tool_decision`, `tool_result`, `mcp_server_connection`, and `permission_mode_changed` events, which export as log records named with a `claude_code.` prefix, become a per-user audit trail you can forward to a Security Information and Event Management (SIEM) platform. See [Audit security events](</docs/en/monitoring-usage#audit-security-events>) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries.
##
--- a/observability.md
+++ b/observability.md
@@ -1,9 +1,3 @@
-> ## Documentation Index
->
-> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
->
-> Use this file to discover all available pages before exploring further.
-
When you run agents in production, you need visibility into what they did:
* which tools they called
--- a/observability.md
+++ b/observability.md
@@ -118,7 +118,7 @@
Link traces to your application
-The SDK automatically propagates W3C trace context into the CLI subprocess. When you call `query()` while an OpenTelemetry span is active in your application, the SDK injects `TRACEPARENT` and `TRACESTATE` into the child process environment, and the CLI reads them so its `claude_code.interaction` span becomes a child of your span. The agent run then appears inside your application’s trace instead of as a disconnected root. The CLI also forwards `TRACEPARENT` to every Bash and PowerShell command it runs. If a command launched through the Bash tool emits its own OpenTelemetry spans, those spans nest under the `claude_code.tool.execution` span that wraps the command. Auto-injection is skipped when you set `TRACEPARENT` explicitly in `options.env`, so you can pin a specific parent context if needed. Interactive CLI sessions ignore inbound `TRACEPARENT` entirely; only Agent SDK and `claude -p` runs honor it. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the full span and attribute reference.
+The SDK automatically propagates W3C trace context into the CLI subprocess. When you call `query()` while an OpenTelemetry span is active in your application, the SDK injects `TRACEPARENT` and `TRACESTATE` into the child process environment, and the CLI reads them so its `claude_code.interaction` span becomes a child of your span. The agent run then appears inside your application’s trace instead of as a disconnected root. When trace-context propagation is enabled, the CLI also forwards `TRACEPARENT` to every Bash and PowerShell command it runs. If a command launched through the Bash tool emits its own OpenTelemetry spans, those spans nest under the `claude_code.tool.execution` span that wraps the command. Auto-injection is skipped when you set `TRACEPARENT` explicitly in `options.env`, so you can pin a specific parent context if needed. Interactive CLI sessions ignore inbound `TRACEPARENT` entirely; only Agent SDK and `claude -p` runs honor it. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the full span and attribute reference.
##
--- a/observability.md
+++ b/observability.md
@@ -144,6 +144,29 @@
+Attribute actions to your end users
+
+The CLI attaches [identity attributes](</docs/en/monitoring-usage#standard-attributes>) to every event based on the credential it uses to call Anthropic. When you build an application that serves many end users from one deployment, these attributes identify your service’s credential, not the end user on whose behalf the agent acted. To make tool calls and MCP activity attributable to your application’s end users, inject end-user identity as resource attributes on each `query()` call. Percent-encode values before interpolating them, since `OTEL_RESOURCE_ATTRIBUTES` [reserves commas, spaces, and equals signs](</docs/en/monitoring-usage#multi-team-organization-support>). The following example attaches the requesting user and tenant to every span and event from one request:
+
+Python
+
+TypeScript
+
+ from urllib.parse import quote
+
+ options = ClaudeAgentOptions(
+ env={
+ # ... exporter configuration ...
+ "OTEL_RESOURCE_ATTRIBUTES": f"enduser.id={quote(request.user_id)},tenant.id={quote(request.tenant_id)}",
+ },
+ )
+
+With end-user identity attached, the `tool_decision`, `tool_result`, `mcp_server_connection`, and `permission_mode_changed` events become a per-user audit trail you can forward to a Security Information and Event Management (SIEM) platform. See [Audit security events](</docs/en/monitoring-usage#audit-security-events>) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries.
+
+##
+
+
+
Control sensitive data in exports
Telemetry is structural by default. Durations, model names, and tool names are recorded on every span; token counts are recorded when the underlying API request returns usage data, so spans for failed or aborted requests may omit them. The content your agent reads and writes is not recorded by default. These opt-in variables add content to the exported data:
--- a/observability.md
+++ b/observability.md
@@ -1,3 +1,9 @@
+> ## Documentation Index
+>
+> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
+>
+> Use this file to discover all available pages before exploring further.
+
When you run agents in production, you need visibility into what they did:
* which tools they called
--- a/observability.md
+++ b/observability.md
@@ -100,11 +100,19 @@
* **`claude_code.interaction`:** wraps a single turn of the agent loop, from receiving a prompt to producing a response.
* **`claude_code.llm_request`:** wraps each call to the Claude API, with model name, latency, and token counts as attributes.
* **`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`).
- * **`claude_code.hook`:** wraps each [hook](</docs/en/agent-sdk/hooks>) execution.
+ * **`claude_code.hook`:** wraps each [hook](</docs/en/agent-sdk/hooks>) execution. Requires detailed beta tracing (`ENABLE_BETA_TRACING_DETAILED=1` and `BETA_TRACING_ENDPOINT`) in addition to the variables above.
-Spans carry a `session.id` attribute by default. When you make several `query()` calls against the same [session](</docs/en/agent-sdk/sessions>), filter on `session.id` in your backend to see them as one timeline. The attribute is omitted if `OTEL_METRICS_INCLUDE_SESSION_ID` is set to a falsy value.
+The `llm_request`, `tool`, and `hook` spans are children of the enclosing `claude_code.interaction` span. When the agent spawns a subagent through the Task tool, the subagent’s `llm_request` and `tool` spans nest under the parent agent’s `claude_code.tool` span, so the full delegation chain appears as one trace. Spans carry a `session.id` attribute by default. When you make several `query()` calls against the same [session](</docs/en/agent-sdk/sessions>), filter on `session.id` in your backend to see them as one timeline. The attribute is omitted if `OTEL_METRICS_INCLUDE_SESSION_ID` is set to a falsy value.
Tracing is in beta. Span names and attributes may change between releases. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the trace exporter configuration variables.
+
+##
+
+
+
+Link traces to your application
+
+The SDK automatically propagates W3C trace context into the CLI subprocess. When you call `query()` while an OpenTelemetry span is active in your application, the SDK injects `TRACEPARENT` and `TRACESTATE` into the child process environment, and the CLI reads them so its `claude_code.interaction` span becomes a child of your span. The agent run then appears inside your application’s trace instead of as a disconnected root. The CLI also forwards `TRACEPARENT` to every Bash and PowerShell command it runs. If a command launched through the Bash tool emits its own OpenTelemetry spans, those spans nest under the `claude_code.tool.execution` span that wraps the command. Auto-injection is skipped when you set `TRACEPARENT` explicitly in `options.env`, so you can pin a specific parent context if needed. Interactive CLI sessions ignore inbound `TRACEPARENT` entirely; only Agent SDK and `claude -p` runs honor it. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the full span and attribute reference.
##
@@ -132,13 +140,14 @@
Control sensitive data in exports
-Telemetry is structural by default. Durations, model names, and tool names are recorded on every span; token counts are recorded when the underlying API request returns usage data, so spans for failed or aborted requests may omit them. The content your agent reads and writes is not recorded by default. Three opt-in variables add content to the exported data:
+Telemetry is structural by default. Durations, model names, and tool names are recorded on every span; token counts are recorded when the underlying API request returns usage data, so spans for failed or aborted requests may omit them. The content your agent reads and writes is not recorded by default. These opt-in variables add content to the exported data:
Variable| Adds
---|---
`OTEL_LOG_USER_PROMPTS=1`| Prompt text on `claude_code.user_prompt` events and on the `claude_code.interaction` span
`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments (file paths, shell commands, search patterns) on `claude_code.tool_result` events
`OTEL_LOG_TOOL_CONTENT=1`| Full tool input and output bodies as span events on `claude_code.tool`, truncated at 60 KB. Requires tracing to be enabled
+`OTEL_LOG_RAW_API_BODIES`| Full Anthropic Messages API request and response JSON as `claude_code.api_request_body` and `claude_code.api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB, or `file:<dir>` for untruncated bodies on disk with a `body_ref` path in the event. Bodies include the entire conversation history and have extended-thinking content redacted. Enabling this implies consent to everything the three variables above would reveal
Leave these unset unless your observability pipeline is approved to store the data your agent handles. See [Security and privacy](</docs/en/monitoring-usage#security-and-privacy>) in the Monitoring reference for the full list of attributes and redaction behavior.
--- a/observability.md
+++ b/observability.md
@@ -76,7 +76,7 @@
Flush telemetry from short-lived calls
-The CLI batches telemetry and exports on an interval. It flushes any pending data when the process exits cleanly, so a `query()` call that completes normally does not lose spans. However, if your process is killed before the CLI shuts down, anything still in the batch buffer is lost. Lowering the export intervals reduces that window. By default, metrics export every 60 seconds and traces and logs export every 5 seconds. The following example shortens all three intervals so that data reaches the collector while a short task is still running:
+The CLI batches telemetry and exports on an interval. On a clean process exit it attempts to flush pending data, but the flush is bounded by a short timeout, so spans can still be dropped if the collector is slow to respond. If your process is killed before the CLI shuts down, anything still in the batch buffer is lost. Lowering the export intervals reduces both windows. By default, metrics export every 60 seconds and traces and logs export every 5 seconds. The following example shortens all three intervals so that data reaches the collector while a short task is still running:
Python
@@ -102,7 +102,7 @@
* **`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`).
* **`claude_code.hook`:** wraps each [hook](</docs/en/agent-sdk/hooks>) execution.
-Every span carries a `session.id` attribute. When you make several `query()` calls against the same [session](</docs/en/agent-sdk/sessions>), filter on `session.id` in your backend to see them as one timeline.
+Spans carry a `session.id` attribute by default. When you make several `query()` calls against the same [session](</docs/en/agent-sdk/sessions>), filter on `session.id` in your backend to see them as one timeline. The attribute is omitted if `OTEL_METRICS_INCLUDE_SESSION_ID` is set to a falsy value.
Tracing is in beta. Span names and attributes may change between releases. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the trace exporter configuration variables.
@@ -132,7 +132,7 @@
Control sensitive data in exports
-Telemetry is structural by default. Token counts, durations, model names, and tool names are always recorded, but the content your agent reads and writes is not. Three opt-in variables add content to the exported data:
+Telemetry is structural by default. Durations, model names, and tool names are recorded on every span; token counts are recorded when the underlying API request returns usage data, so spans for failed or aborted requests may omit them. The content your agent reads and writes is not recorded by default. Three opt-in variables add content to the exported data:
Variable| Adds
---|---
Show diff (158 lines)
--- a/observability.md
+++ b/observability.md
@@ -0,0 +1,155 @@
+When you run agents in production, you need visibility into what they did:
+
+ * which tools they called
+ * how long each model request took
+ * how many tokens were spent
+ * where failures occurred
+
+The Agent SDK can export this data as OpenTelemetry traces, metrics, and log events to any backend that accepts the OpenTelemetry Protocol (OTLP), such as Honeycomb, Datadog, Grafana, Langfuse, or a self-hosted collector. This guide explains how the SDK emits telemetry, how to configure the export, and how to tag and filter the data once it reaches your backend. To read token usage and cost directly from the SDK response stream instead of exporting to a backend, see [Track cost and usage](</docs/en/agent-sdk/cost-tracking>).
+
+##
+
+
+
+How telemetry flows from the SDK
+
+The Agent SDK runs the Claude Code CLI as a child process and communicates with it over a local pipe. The CLI has OpenTelemetry instrumentation built in: it records spans around each model request and tool execution, emits metrics for token and cost counters, and emits structured log events for prompts and tool results. The SDK does not produce telemetry of its own. Instead, it passes configuration through to the CLI process, and the CLI exports directly to your collector. Configuration is passed as environment variables. By default, the child process inherits your application’s environment, so you can configure telemetry in either of two places:
+
+ * **Process environment:** set the variables in your shell, container, or orchestrator before your application starts. Every `query()` call picks them up automatically with no code change. This is the recommended approach for production deployments.
+ * **Per-call options:** set the variables in `ClaudeAgentOptions.env` (Python) or `options.env` (TypeScript). Use this when different agents in the same process need different telemetry settings. In Python, `env` is merged on top of the inherited environment. In TypeScript, `env` replaces the inherited environment entirely, so include `...process.env` in the object you pass.
+
+The CLI exports three independent OpenTelemetry signals. Each has its own enable switch and its own exporter, so you can turn on only the ones you need.
+
+Signal| What it contains| Enable with
+---|---|---
+Metrics| Counters for tokens, cost, sessions, lines of code, and tool decisions| `OTEL_METRICS_EXPORTER`
+Log events| Structured records for each prompt, API request, API error, and tool result| `OTEL_LOGS_EXPORTER`
+Traces| Spans for each interaction, model request, tool call, and hook (beta)| `OTEL_TRACES_EXPORTER` plus `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`
+
+For the complete list of metric names, event names, and attributes, see the Claude Code [Monitoring](</docs/en/monitoring-usage>) reference. The Agent SDK emits the same data because it runs the same CLI. Span names are listed in Read agent traces below.
+
+##
+
+
+
+Enable telemetry export
+
+Telemetry is off until you set `CLAUDE_CODE_ENABLE_TELEMETRY=1` and choose at least one exporter. The most common configuration sends all three signals over OTLP HTTP to a collector. The following example sets the variables in a dictionary and passes them through `options.env`. The agent runs a single task, and the CLI exports spans, metrics, and events to the collector at `collector.example.com` while the loop consumes the response stream:
+
+Python
+
+TypeScript
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions
+
+ OTEL_ENV = {
+ "CLAUDE_CODE_ENABLE_TELEMETRY": "1",
+ # Required for traces, which are in beta. Metrics and log events do not need this.
+ "CLAUDE_CODE_ENHANCED_TELEMETRY_BETA": "1",
+ # Choose an exporter per signal. Use otlp for the SDK; see the Note below.
+ "OTEL_TRACES_EXPORTER": "otlp",
+ "OTEL_METRICS_EXPORTER": "otlp",
+ "OTEL_LOGS_EXPORTER": "otlp",
+ # Standard OTLP transport configuration.
+ "OTEL_EXPORTER_OTLP_PROTOCOL": "http/protobuf",
+ "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.example.com:4318",
+ "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer your-token",
+ }
+
+ async def main():
+ options = ClaudeAgentOptions(env=OTEL_ENV)
+ async for message in query(
+ prompt="List the files in this directory", options=options
+ ):
+ print(message)
+
+ asyncio.run(main())
+
+Because the child process inherits your application’s environment by default, you can achieve the same result by exporting these variables in a Dockerfile, Kubernetes manifest, or shell profile and omitting `options.env` entirely.
+
+The `console` exporter writes telemetry to standard output, which the SDK uses as its message channel. Do not set `console` as an exporter value when running through the SDK. To inspect telemetry locally, point `OTEL_EXPORTER_OTLP_ENDPOINT` at a local collector or an all-in-one Jaeger container instead.
+
+###
+
+
+
+Flush telemetry from short-lived calls
+
+The CLI batches telemetry and exports on an interval. It flushes any pending data when the process exits cleanly, so a `query()` call that completes normally does not lose spans. However, if your process is killed before the CLI shuts down, anything still in the batch buffer is lost. Lowering the export intervals reduces that window. By default, metrics export every 60 seconds and traces and logs export every 5 seconds. The following example shortens all three intervals so that data reaches the collector while a short task is still running:
+
+Python
+
+TypeScript
+
+ OTEL_ENV = {
+ # ... exporter configuration from the previous example ...
+ "OTEL_METRIC_EXPORT_INTERVAL": "1000",
+ "OTEL_LOGS_EXPORT_INTERVAL": "1000",
+ "OTEL_TRACES_EXPORT_INTERVAL": "1000",
+ }
+
+##
+
+
+
+Read agent traces
+
+Traces give you the most detailed view of an agent run. With `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1` set, each step of the agent loop becomes a span you can inspect in your tracing backend:
+
+ * **`claude_code.interaction`:** wraps a single turn of the agent loop, from receiving a prompt to producing a response.
+ * **`claude_code.llm_request`:** wraps each call to the Claude API, with model name, latency, and token counts as attributes.
+ * **`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`).
+ * **`claude_code.hook`:** wraps each [hook](</docs/en/agent-sdk/hooks>) execution.
+
+Every span carries a `session.id` attribute. When you make several `query()` calls against the same [session](</docs/en/agent-sdk/sessions>), filter on `session.id` in your backend to see them as one timeline.
+
+Tracing is in beta. Span names and attributes may change between releases. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the trace exporter configuration variables.
+
+##
+
+
+
+Tag telemetry from your agent
+
+By default, the CLI reports `service.name` as `claude-code`. If you run several agents, or run the SDK alongside other services that export to the same collector, override the service name and add resource attributes so you can filter by agent in your backend. The following example renames the service and attaches deployment metadata. These values are applied as OpenTelemetry resource attributes on every span, metric, and event the agent emits:
+
+Python
+
+TypeScript
+
+ options = ClaudeAgentOptions(
+ env={
+ # ... exporter configuration ...
+ "OTEL_SERVICE_NAME": "support-triage-agent",
+ "OTEL_RESOURCE_ATTRIBUTES": "service.version=1.4.0,deployment.environment=production",
+ },
+ )
+
+##
+
+
+
+Control sensitive data in exports
+
+Telemetry is structural by default. Token counts, durations, model names, and tool names are always recorded, but the content your agent reads and writes is not. Three opt-in variables add content to the exported data:
+
+Variable| Adds
+---|---
+`OTEL_LOG_USER_PROMPTS=1`| Prompt text on `claude_code.user_prompt` events and on the `claude_code.interaction` span
+`OTEL_LOG_TOOL_DETAILS=1`| Tool input arguments (file paths, shell commands, search patterns) on `claude_code.tool_result` events
+`OTEL_LOG_TOOL_CONTENT=1`| Full tool input and output bodies as span events on `claude_code.tool`, truncated at 60 KB. Requires tracing to be enabled
+
+Leave these unset unless your observability pipeline is approved to store the data your agent handles. See [Security and privacy](</docs/en/monitoring-usage#security-and-privacy>) in the Monitoring reference for the full list of attributes and redaction behavior.
+
+##
+
+
+
+Related documentation
+
+These guides cover adjacent topics for monitoring and deploying agents:
+
+ * [Track cost and usage](</docs/en/agent-sdk/cost-tracking>): read token and cost data from the message stream without an external backend.
+ * [Hosting the Agent SDK](</docs/en/agent-sdk/hosting>): deploy agents in containers where you can set OpenTelemetry variables at the environment level.
+ * [Monitoring](</docs/en/monitoring-usage>): the complete reference for every environment variable, metric, and event the CLI emits.