modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -30,6 +30,8 @@ To verify a setup that exports metrics, check your backend for the `claude_code.session.count` metric, which Claude Code emits when a session starts. To verify a logs-only setup, submit a prompt and check for the `claude_code.user_prompt` event. If nothing arrives, start Claude Code with `claude --debug-file <path>` and check the log it writes to that path. Claude Code reports failures from the exporters you configure as `[3P telemetry]` errors, where 3P means third-party. Lines prefixed `[Anthropic telemetry]` describe [Anthropic’s separate operational telemetry](</docs/en/data-usage#telemetry-services>) and don’t indicate a problem with your setup. For full configuration options, see the [OpenTelemetry specification](<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options>). ## Administrator configuration + +If you set **OTLP endpoint** under **Telemetry & updates** in the [Enterprise Admin Console](<https://claude.com/docs/third-party/claude-desktop/admin-console-claude-code>), terminal sessions that export there don’t follow your endpoint, protocol, or gRPC certificate variables. To send their data somewhere else, change that field in the console. If you set `OTEL_EXPORTER_OTLP_ENDPOINT`, even in managed settings, those sessions still export to the console’s collector.Run `/status` to check a session on Claude Code v2.1.331 or later. Only terminal sessions that get their collector from the console show a **Telemetry** row, which lists that collector’s host. If the row starts with `not sent to`, the session isn’t exporting. See [which computers follow the console](<https://claude.com/docs/third-party/claude-desktop/admin-console-claude-code#which-settings-take-priority>), [what else it replaces](<https://claude.com/docs/third-party/claude-desktop/admin-console-claude-code-reference#managed-settings-beside-the-console>), and which certificate variables to set. Administrators can configure OpenTelemetry settings for all users through the [managed settings file](</docs/en/managed-settings#delivery-mechanisms>). See the [settings precedence](</docs/en/settings#settings-precedence>) for more information about how settings are applied. Example managed settings configuration: @@ -48,7 +50,7 @@ ### How managed settings lock the OTLP destination -When you set an `OTEL_EXPORTER_OTLP_*` variable in managed settings, Claude Code removes conflicting developer-set variables at startup and logs a warning in the debug log. What it removes depends on which variable you set: +Skip this section for sessions that export to the Enterprise Admin Console’s collector. When you set an `OTEL_EXPORTER_OTLP_*` variable in managed settings, Claude Code removes conflicting developer-set variables at startup and logs a warning in the debug log. What it removes depends on which variable you set: * **Endpoints** : when you set `OTEL_EXPORTER_OTLP_ENDPOINT`, Claude Code removes every developer-set per-signal endpoint. Developers can’t point one signal at a different collector, so you don’t need to also set the per-signal endpoint variables in managed settings. * **Protocols** : when you set `OTEL_EXPORTER_OTLP_PROTOCOL`, Claude Code removes every developer-set per-signal protocol. @@ -90,7 +92,7 @@ `OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, user-authored workflow names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events, and real agent, skill, plugin, and MCP server and tool names on the cost and token counters (default: disabled). For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `mcp_server_name`/`mcp_tool_name` emit on `tool_decision`/`tool_result` even with the flag off. The exception requires Claude Code v2.1.214 or later| `1` to enable `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool content in the `tool.output` span event (default: disabled). Span attributes carry tool content under their own gates. Requires tracing. Content is truncated at the content limit (60 KB by default)| `1` to enable `OTEL_LOG_MANAGED_SETTINGS`| Add the redacted managed settings, and a SHA-256 digest of the settings before redaction, to managed settings resolved events (default: disabled). A value in project or local settings doesn’t turn it on. Requires Claude Code v2.1.274 or later| `1` to enable -`OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). Bodies can 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| `1` for inline bodies truncated at the content limit (60 KB by default), or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event +`OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). Bodies can 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. In [Code Mode](</docs/en/code-mode#trace-calls-from-code>), your backend can receive output through the last two that the bodies lack| `1` for inline bodies truncated at the content limit (60 KB by default), or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`| Content limit: the maximum length of content-bearing attributes such as model responses, tool content, system prompts, and raw API bodies, truncation marker included, in UTF-16 code units (default: 61440, i.e. 60 KB). The default is sized for backends that cap attribute values at 64 KB; raise it only if your backend accepts larger values, or lower it to cut telemetry volume. When an OpenTelemetry SDK attribute limit, `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` or one of its logrecord and span variants, is set lower, Claude Code truncates at that smaller value so the `[TRUNCATED ...]` marker stays within the SDK limit| `262144` `OTEL_RESOURCE_INCLUDE_HOST`| Add the machine’s name and ID to the resource attributes of metrics, events, and traces (default: disabled). See Identify the machine a session ran on. Requires Claude Code v2.1.326 or later| `1` to enable `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` @@ -107,7 +109,7 @@ `http/protobuf`, `http/json`| `CLAUDE_CODE_CLIENT_CERT`, `CLAUDE_CODE_CLIENT_KEY`, and optionally `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE`. See [Network configuration](</docs/en/network-config#mtls-authentication>)| `NODE_EXTRA_CA_CERTS` `grpc`| `OTEL_EXPORTER_OTLP_CLIENT_KEY` and `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`, or the per-signal variants such as `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` to use a different certificate per signal| `OTEL_EXPORTER_OTLP_CERTIFICATE` -For `grpc`, the OpenTelemetry SDK reads the standard OTLP variables directly, so existing configurations that set the per-signal metrics variables continue to work. On machines with managed settings, Claude Code may remove developer-set per-signal credentials and endpoints at startup. +For `grpc`, the OpenTelemetry SDK reads the standard OTLP variables directly, so existing configurations that set the per-signal metrics variables continue to work. On machines with managed settings, Claude Code may remove developer-set per-signal credentials and endpoints at startup. For a session that exports to the Enterprise Admin Console’s collector, use the variables in the `http/protobuf`, `http/json` row, whichever protocol you chose in the console. Claude Code ignores the variables in the `grpc` row for that collector, including `OTEL_EXPORTER_OTLP_CERTIFICATE`. If the collector uses a private CA, [set `NODE_EXTRA_CA_CERTS`](</docs/en/network-config#custom-ca-certificates>) to trust it. ### Metrics cardinality control @@ -172,7 +174,7 @@ #### Span hierarchy -Each user prompt starts a `claude_code.interaction` root span. API calls, tool calls, and hook executions are recorded as its children. Tool spans have two child spans of their own: one for the time spent waiting on a permission decision and one for the execution itself. When the Agent tool, or legacy Task tool, spawns a subagent, the subagent’s API and tool spans nest under the parent’s `claude_code.tool` span. +Each user prompt starts a `claude_code.interaction` root span. API calls, tool calls, and hook executions are recorded as its children. Tool spans have two child spans of their own: one for the time spent waiting on a permission decision and one for the execution itself. When the Agent tool, or legacy Task tool, spawns a subagent, the subagent’s API and tool spans nest under the parent’s `claude_code.tool` span. In Code Mode, [calls from code](</docs/en/code-mode#trace-calls-from-code>) nest under the `REPL` tool’s `claude_code.tool.execution` span. claude_code.interaction ├── claude_code.llm_request @@ -245,7 +247,7 @@ `parent_agent_id`| Identifier of the agent that spawned this one. Absent for the main session and for agents spawned directly from it| `workflow.run_id`| Run identifier of the Workflow tool run that spawned this agent, prefixed `wf_`. Absent for agents not spawned by a workflow| `workflow.name`| Name of the workflow that spawned this agent. User-authored names are replaced with `custom` unless the gate is set| `OTEL_LOG_TOOL_DETAILS` -`tool_use_id`| The model’s `tool_use` block id for this call. Matches the `tool_use_id` on the tool_result and tool_decision events and in hook payloads, so you can join the span to those records| +`tool_use_id`| The model’s `tool_use` block id for this call, or an ID that Claude Code generates for a [call from code](</docs/en/code-mode#monitor-code-mode-with-opentelemetry>) in Code Mode. Matches the `tool_use_id` on the tool_result and tool_decision events and in hook payloads, so you can join the span to those records| `gen_ai.tool.call.id`| Same value as `tool_use_id`. OpenTelemetry GenAI semantic convention| `file_path`| Target file path for Read, Edit, and Write tools| `OTEL_LOG_TOOL_DETAILS` `full_command`| Command string for the Bash tool| `OTEL_LOG_TOOL_DETAILS` @@ -318,7 +320,7 @@ `system_prompt_preview`| `claude_code.llm_request`| First 500 characters of the complete system prompt sent with the request| `OTEL_LOG_USER_PROMPTS` `user_system_prompt`| `claude_code.llm_request`| Only the system prompt text you provide via the `systemPrompt` SDK option or `--system-prompt` and `--append-system-prompt` flags. Emitted once per session rather than per request| `OTEL_LOG_USER_PROMPTS` `response.model_output`| `claude_code.llm_request`| Text of the model’s response to the request| `OTEL_LOG_USER_PROMPTS` -`new_context`| `claude_code.tool`| The tool call’s result, whatever the tool| `OTEL_LOG_TOOL_CONTENT` +`new_context`| `claude_code.tool`| The tool call’s result. Absent for `REPL` and `Poll`, the tools that run [Code Mode](</docs/en/code-mode#trace-calls-from-code>) code and return its output| `OTEL_LOG_TOOL_CONTENT` `tool_input`| `claude_code.tool`| The tool call’s serialized input| `OTEL_LOG_TOOL_DETAILS` Under detailed beta tracing with `OTEL_LOG_USER_PROMPTS=1`, Claude Code also emits a `claude_code.system_prompt` event that carries the complete system prompt, truncated at the content limit. It arrives the first time a session sends each distinct system prompt, and again after compaction. @@ -477,6 +479,7 @@ * **Let sessions reach the collector** : Claude Code sends the export through the session’s network, so whether it reaches the host in your `OTEL_EXPORTER_OTLP_ENDPOINT` depends on the environment’s [network access level](</docs/en/cloud-environments#access-levels>). If sessions can’t reach the collector’s domain at the level you chose, [add the domain to the environment’s allowlist](</docs/en/cloud-environments#allow-specific-domains>), because no server-managed setting adds domains to an environment’s network allowlist. * **Claude Tag channels** : make the allowlist and any environment-variable changes on the [shared environment](</docs/en/cloud-environments#organization-shared-environments>) set as your organization’s default or pinned to the channel. + * **Start a new session after you change the allowlist** : the telemetry export doesn’t pick up [allowlist changes](</docs/en/cloud-environments#network-access>) in a session that’s already running. In a Claude Tag channel, send [`@Claude !restart`](<https://claude.com/docs/claude-tag/users/commands#restart-a-stuck-or-wrong-context-session>). * **Cowork is configured separately** : Cowork sessions don’t receive server-managed settings, as the [surface coverage table](</docs/en/model-config#surface-coverage>) shows, so the server-managed `env` block doesn’t configure their telemetry. ### Attribute telemetry to cloud sessions @@ -1059,7 +1062,7 @@ * `skill_path_count`: number of skill directories the plugin declares * `command_path_count`: number of command directories the plugin declares * `agent_path_count`: number of agent directories the plugin declares - * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. In safe mode this event reports configured inventory only; the plugin’s commands, skills, hooks, and MCP servers don’t load. Requires Claude Code v2.1.169 or later + * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. In safe mode, this event also fires for plugins that don’t load. Requires Claude Code v2.1.169 or later #### Skill activated event @@ -1457,7 +1460,7 @@ ### Send events to a SIEM -Point `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` at your SIEM’s OTLP receiver, or at an OpenTelemetry Collector that forwards to your SIEM’s native ingest API. The following managed-settings example exports events only, with full tool detail enabled for MCP and Bash auditing: +For sessions that export to the Enterprise Admin Console’s collector, skip these steps and forward events to your SIEM from that collector. Point `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` at your SIEM’s OTLP receiver, or at an OpenTelemetry Collector that forwards to your SIEM’s native ingest API. The following managed-settings example exports events only, with full tool detail enabled for MCP and Bash auditing: { "env": { @@ -1545,6 +1548,7 @@ * Raw Anthropic Messages API request and response bodies aren’t logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES` in your shell, user settings, or managed settings. It’s ignored in [project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). The bodies can contain the full conversation history, including the system prompt, every prior user and assistant turn, and tool results. Enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude Code always redacts Claude’s extended-thinking content from these bodies, regardless of other settings. The value you set determines how Claude Code delivers the bodies: * With `=1`, Claude Code emits `api_request_body` and `api_response_body` log events for each API call. The events’ `body` attribute carries the JSON-serialized payload, truncated at the content limit (60 KB by default) * With `=file:<dir>`, Claude Code writes untruncated bodies to `.request.json` and `.response.json` files under that directory, and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. For each successful response, Claude Code also appends one line to `index.jsonl` in that directory, linking the response file to the request file that produced it and to the transcript message it became. Each line holds no message content, and the API response body event section lists its fields. The index file requires Claude Code v2.1.274 or later + * In [Code Mode](</docs/en/code-mode#trace-calls-from-code>), review `OTEL_LOG_TOOL_CONTENT` and `OTEL_LOG_TOOL_DETAILS` separately from raw bodies. With either set, your backend can receive output that code read but didn’t return to Claude, which the bodies can lack * The machine’s name and ID aren’t included by default. To include them as `host.name` and `host.id`, set `OTEL_RESOURCE_INCLUDE_HOST=1`. A host name often contains a person’s name, and `host.id` is a lasting identifier for the machine. If you set the variable in managed settings, tell the people who use those machines, because Claude Code shows them no notice. ## Monitor Claude Code on Amazon Bedrock
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1162,7 +1162,7 @@ #### Hook plugin metrics event -Logged when an official-marketplace plugin hook emits per-invocation metrics. Only plugins installed from an official Anthropic marketplace can emit these. Third-party marketplace plugins and user-configured hooks don’t emit to this event. Use this event to monitor plugin behavior such as finding rates, costs, and durations from your own observability stack. **Event Name** : `claude_code.hook_plugin_metrics` **Attributes** : +Logged when an official-marketplace plugin hook emits per-invocation metrics. Only plugins installed from an official Anthropic marketplace can emit these. Use this event to monitor plugin behavior such as finding rates, costs, and durations from your own observability stack. **Event Name** : `claude_code.hook_plugin_metrics` **Attributes** : * All standard attributes * `event.name`: `"hook_plugin_metrics"`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -90,7 +90,7 @@ `OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, user-authored workflow names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events, and real agent, skill, plugin, and MCP server and tool names on the cost and token counters (default: disabled). For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `mcp_server_name`/`mcp_tool_name` emit on `tool_decision`/`tool_result` even with the flag off. The exception requires Claude Code v2.1.214 or later| `1` to enable `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool content in the `tool.output` span event (default: disabled). Span attributes carry tool content under their own gates. Requires tracing. Content is truncated at the content limit (60 KB by default)| `1` to enable `OTEL_LOG_MANAGED_SETTINGS`| Add the redacted managed settings, and a SHA-256 digest of the settings before redaction, to managed settings resolved events (default: disabled). A value in project or local settings doesn’t turn it on. Requires Claude Code v2.1.274 or later| `1` to enable -`OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). 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| `1` for inline bodies truncated at the content limit (60 KB by default), or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event +`OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). Bodies can 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| `1` for inline bodies truncated at the content limit (60 KB by default), or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`| Content limit: the maximum length of content-bearing attributes such as model responses, tool content, system prompts, and raw API bodies, truncation marker included, in UTF-16 code units (default: 61440, i.e. 60 KB). The default is sized for backends that cap attribute values at 64 KB; raise it only if your backend accepts larger values, or lower it to cut telemetry volume. When an OpenTelemetry SDK attribute limit, `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` or one of its logrecord and span variants, is set lower, Claude Code truncates at that smaller value so the `[TRUNCATED ...]` marker stays within the SDK limit| `262144` `OTEL_RESOURCE_INCLUDE_HOST`| Add the machine’s name and ID to the resource attributes of metrics, events, and traces (default: disabled). See Identify the machine a session ran on. Requires Claude Code v2.1.326 or later| `1` to enable `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` @@ -641,7 +641,7 @@ ---|--- `prompt.id`| UUID v4 identifier linking all events produced while processing a single user prompt `event.sequence`| 0-based counter for ordering events, counted per Claude Code process rather than per session -`message.uuid`| UUID of the message as persisted in the session transcript, the `~/.claude/projects/*/*.jsonl` files. Present on `assistant_response`, on `api_response_body`, and on `user_prompt` except for command dispatches, which can produce zero or many messages. On `assistant_response` and `api_response_body`, this is the response’s final transcript entry, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.274 or later on `api_response_body` +`message.uuid`| UUID of the message as persisted in the session transcript, the `~/.claude/projects/*/*.jsonl` files. Present on `assistant_response`, on `api_response_body`, and on `user_prompt` except for command dispatches, which can produce zero or many messages. On `api_response_body`, and on an `assistant_response` event without a `tool_use_id`, this is the response’s final transcript entry, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.274 or later on `api_response_body` `request_id`| Server-assigned ID of the API request, read from the `request-id` response header, such as `req_011...`. On a response with no `request-id` header, as on [Amazon Bedrock](</docs/en/amazon-bedrock>), the value comes from the `x-amzn-requestid` header instead. Present on `api_request`, `api_error`, `api_refusal`, `assistant_response`, `api_response_body`, `tool_result`, and `tool_decision` when the response carries either header. Matches the same attribute on the `llm_request` trace span. The `x-amzn-requestid` source requires Claude Code v2.1.282 or later `client_request_id`| Client-generated UUID sent as the `x-client-request-id` request header. Present on `api_request` and `api_error` on first-party API connections; absent on third-party provider backends and when the request was retried through the non-streaming fallback. Pairs a request with its response and remains available for failures such as timeouts that never produced a server `request_id`. Matches the same attribute on the `llm_request` trace span @@ -649,7 +649,7 @@ * `message.uuid` on `user_prompt`, `assistant_response`, and `api_response_body` * `request_id` on the API events, persisted as `requestId` on the transcript’s assistant entries - * `tool_use_id` on `tool_result` and `tool_decision` events, and on `safety_event` events except those for the end of a turn + * `tool_use_id` on `tool_result` and `tool_decision` events, on `assistant_response` events for messages sent with a tool, and on `safety_event` events except those for the end of a turn #### User prompt event @@ -668,7 +668,12 @@ #### Assistant response event -Logged after each API request that returns text content from the model. Only the response’s text blocks are included; thinking blocks and tool-use blocks are excluded. **Event Name** : `claude_code.assistant_response` **Attributes** : +An `assistant_response` event holds either the text of an API response or a message that Claude wrote to the user by calling a tool. The `tool_use_id` attribute tells you which: + + * **Text reply, no`tool_use_id`**: logged after each API request that returns text content from the model. Only the response’s text blocks are included; thinking blocks and tool-use blocks are excluded. + * **Message sent with a tool, has`tool_use_id`**: `response` holds the message text from a successful call to `SendUserMessage` or Cowork’s `mcp__cowork__send_user_message`. Claude Code logs the event before [`PostToolUse`](</docs/en/hooks#posttooluse>) hooks run. Requires Claude Code v2.1.332 or later. + +You receive `assistant_response` events with `tool_use_id` only while you include response text, as described under `response`. **Event Name** : `claude_code.assistant_response` **Attributes** : * All standard attributes * `event.name`: `"assistant_response"` @@ -677,8 +682,9 @@ * `response_length`: Length of the response text in characters * `response`: Response text, truncated at the content limit (60 KB by default). Redacted to `<REDACTED>` by default. Set `OTEL_LOG_ASSISTANT_RESPONSES=1` to include it. When `OTEL_LOG_ASSISTANT_RESPONSES` is unset, `OTEL_LOG_USER_PROMPTS` controls it instead, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` to keep responses redacted while prompt logging is on * `model`: Model identifier (for example, “claude-sonnet-5”) - * `request_id`: API request ID, described under Event correlation attributes - * `message.uuid`: UUID of the response’s final transcript entry. An API response is persisted as one transcript entry per content block; this is the last one, which the next turn’s `parentUuid` chains from. + * `request_id`: API request ID, described under Event correlation attributes. On an event with `tool_use_id`, this is the ID of the API response that held the call. When that response also has text, both kinds of event share one `request_id` + * `tool_use_id`: Present only on an event for a message sent with a tool. Same value as on the call’s tool result event + * `message.uuid`: UUID of a transcript entry. An API response is persisted as one transcript entry per content block. For a text reply, this is the last one, which the next turn’s `parentUuid` chains from. For an event with `tool_use_id`, this is the entry that holds the tool call. * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name #### Tool result event @@ -1267,7 +1273,7 @@ * `"force_refresh_failed"`: the settings fetch that [`forceRemoteSettingsRefresh`](</docs/en/settings-reference#forceremotesettingsrefresh>) requires failed * `"gateway_rejected"`: a [Claude apps gateway](</docs/en/claude-apps-gateway>) answered the managed settings load with HTTP 403 * `"version_below_minimum"`: this version of Claude Code is below [`requiredMinimumVersion`](</docs/en/settings-reference#requiredminimumversion>) or above [`requiredMaximumVersion`](</docs/en/settings-reference#requiredmaximumversion>) - * `"_OTHER"`: the Claude apps gateway managed settings load failed for another reason + * `"_OTHER"`: a cause that has no dedicated value, such as a gateway settings load that failed for another reason * `managed_settings.sources`: every managed source that delivers at least one [policy key](</docs/en/managed-settings#how-claude-code-combines-managed-sources>), highest priority first, including sources whose keys don’t take effect under `first-wins`. Values are `"remote"`, `"plist"` or `"hklm"` for the MDM or OS-level policy, `"file"` for managed settings files and drop-ins, `"parent"` when an [embedding host](</docs/en/managed-settings#let-an-embedding-host-add-policy>) supplies settings, and `"hkcu"` for the [Windows HKCU registry value](</docs/en/managed-settings#where-each-mechanism-stores-the-policy>) when Claude Code [reads it](</docs/en/managed-settings#how-claude-code-combines-managed-sources>). A source that carries only control keys, or that Claude Code couldn’t read, isn’t listed. Emitted as an array of strings, empty when no managed source delivers a policy key * `managed_settings.source_behavior`: the [`managedSourcesBehavior`](</docs/en/settings-reference#managedsourcesbehavior>) value Claude Code read, `"first-wins"` or `"merge"`. `"first-wins"` when no source sets the key * `managed_settings.helper.state`: state of the policy helper that the selected MDM or file source configures: @@ -1536,7 +1542,7 @@ * The cost and token counters and the `api_request`, `api_error`, and `api_refusal` events carry real agent, skill, plugin, and MCP server and tool names in their attribution attributes * The `claude_code.tool` span carries input-derived attributes such as `file_path`. Under detailed beta tracing it also carries a `tool_input` attribute * Tool content is not logged in trace spans by default. 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, and what MCP tools, WebFetch, and WebSearch return, truncated at the content limit (60 KB by default) per attribute. Results from MCP tools, WebFetch, and WebSearch require Claude Code v2.1.283 or later. Tool content also reaches spans through `new_context`, whose gate differs per span. Configure your telemetry backend to filter or redact these attributes as needed - * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES` in your shell, user settings, or managed settings. It’s ignored in [project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). The bodies contain the full conversation history, including the system prompt, every prior user and assistant turn, and tool results, so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude Code always redacts Claude’s extended-thinking content from these bodies, regardless of other settings. The value you set determines how Claude Code delivers the bodies: + * Raw Anthropic Messages API request and response bodies aren’t logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES` in your shell, user settings, or managed settings. It’s ignored in [project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). The bodies can contain the full conversation history, including the system prompt, every prior user and assistant turn, and tool results. Enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude Code always redacts Claude’s extended-thinking content from these bodies, regardless of other settings. The value you set determines how Claude Code delivers the bodies: * With `=1`, Claude Code emits `api_request_body` and `api_response_body` log events for each API call. The events’ `body` attribute carries the JSON-serialized payload, truncated at the content limit (60 KB by default) * With `=file:<dir>`, Claude Code writes untruncated bodies to `.request.json` and `.response.json` files under that directory, and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. For each successful response, Claude Code also appends one line to `index.jsonl` in that directory, linking the response file to the request file that produced it and to the transcript message it became. Each line holds no message content, and the API response body event section lists its fields. The index file requires Claude Code v2.1.274 or later * The machine’s name and ID aren’t included by default. To include them as `host.name` and `host.id`, set `OTEL_RESOURCE_INCLUDE_HOST=1`. A host name often contains a person’s name, and `host.id` is a lasting identifier for the machine. If you set the variable in managed settings, tell the people who use those machines, because Claude Code shows them no notice.
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -255,7 +255,7 @@ **`tool.output` span event on `claude_code.tool`** If you set `OTEL_LOG_TOOL_CONTENT=1`, Read and Bash calls can record a `tool.output` span event on the `claude_code.tool` span. Edit and Write calls record one only when you also set `OTEL_LOG_TOOL_DETAILS=1`. That variable isn’t scoped to those two tools, so check its row in the configuration table for the arguments it adds elsewhere. MCP tools, WebFetch, and WebSearch record this event too, on Claude Code v2.1.283 or later. Claude Code writes this event from a tool call’s successful return, so a call that raises an error records nothing, whatever the tool. Among the calls that do return, it records no `tool.output` event for: * A call to any tool other than Read, Edit, Write, Bash, WebFetch, WebSearch, and MCP tools - * A Read that returns anything other than file text, such as an image, a PDF, or a re-read of a file whose contents haven’t changed + * A Read that returns anything other than file text, such as an image or a PDF * An Edit or Write call, unless you also set `OTEL_LOG_TOOL_DETAILS=1` * A WebFetch or WebSearch call that Claude Code moved to the background while it ran so that a waiting message could reach Claude. The result that arrives later isn’t recorded either. To learn when Claude Code moves a call, see [When Claude Code sends what you queued](</docs/en/interactive-mode#when-claude-code-sends-what-you-queued>) for the terminal and the [`priority` field](</docs/en/agent-sdk/typescript#sdkusermessage>) for Agent SDK sessions
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -691,7 +691,7 @@ * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `tool_name`: Name of the tool * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. - * `request_id`: the `request_id` of the API response that contained this tool call, so you can join the call to that response’s API events. Absent when that response had no request ID, or when no API response contained the call. Requires Claude Code v2.1.310 or later + * `request_id`: the `request_id` of the API response that contained this tool call or the [Code Mode](</docs/en/code-mode#monitor-code-mode-with-opentelemetry>) code that made it. Use it to join the call to that response’s API events. Absent when that response had no request ID, or when no API response contained the call or its code. Requires Claude Code v2.1.310 or later * `success`: `"true"` or `"false"` * `duration_ms`: Execution time in milliseconds * `error_type`: Error category string when the tool failed, such as `"Error:ENOENT"` or `"ShellError"` @@ -819,7 +819,7 @@ * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `tool_name`: Name of the tool (for example, “Read”, “Edit”, “Write”, “NotebookEdit”) * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. - * `request_id`: the `request_id` of the API response that contained this tool call, so you can join the call to that response’s API events. Absent when that response had no request ID, or when no API response contained the call. Requires Claude Code v2.1.310 or later + * `request_id`: the `request_id` of the API response that contained this tool call or the [Code Mode](</docs/en/code-mode#monitor-code-mode-with-opentelemetry>) code that made it. Use it to join the call to that response’s API events. Absent when that response had no request ID, or when no API response contained the call or its code. Requires Claude Code v2.1.310 or later * `decision`: Either `"accept"` or `"reject"` * `tool_source`: Always present. The tool’s provenance, as a closed set of CLI-authored values: * `"builtin"`: the CLI’s own tools @@ -849,6 +849,7 @@ The attribute also appears on plan mode calls when [the classifier reviews commands in plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>). The attribute is absent in these cases: * An allow or deny [permission rule](</docs/en/permissions#manage-permissions>) decided the call * Claude Code approved the call in auto mode without asking the classifier + * In [Code Mode](</docs/en/code-mode#monitor-code-mode-with-opentelemetry>), the classifier’s review of the code covered the call * The user answered the prompt Claude Code showed after [repeated blocks](</docs/en/permission-modes#repeated-block-thresholds>) * In a `-p` run without `--permission-prompt-tool`, Claude Code denied the call after repeated blocks because there was nobody to answer a prompt. That event reports `decision` as `"reject"` and `source` as `"config"` * `classifier_category` (when `OTEL_LOG_TOOL_DETAILS=1`): The name of the [policy](</docs/en/auto-mode-config#fix-a-policy-denial>) or [built-in rule](</docs/en/auto-mode-config#inspect-the-defaults-and-your-effective-config>) the classifier named when it blocked the call, in lowercase with underscores, such as `"data_exfiltration"` for the Data Exfiltration rule. Requires Claude Code v2.1.301 or later. The attribute is present when both of these hold:
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -413,7 +413,7 @@ * **You set it on the computer that runs Desktop** : Desktop doesn’t pass a value you set there to the SSH session * **You exported it in`/etc/profile` or another file that only login shells read**: the name arrives when you run `claude` from a login shell, but not in a Desktop SSH session. Desktop doesn’t start Claude Code through a login shell. Set the variable under `env` in the [managed settings file](</docs/en/desktop#managed-settings>) on the remote machine instead. - * **A value has a space inside it** : Claude Code then copies none of the keys onto events or datapoints. To see which value has the space, run `/status` in a session on the remote machine. Take the space out of the value. + * **A value has a space inside it** : Claude Code can then leave `host.name` off events and datapoints. To see which value has the space, run `/status` in a session on the remote machine. Take the space out of the value. * **Something else already sets the variable** : in a session that the desktop app starts, a variable already set in the launch environment [takes precedence over settings files](</docs/en/settings-reference#how-env-values-interact-with-your-shell>). The [debug log](</docs/en/debug-your-config>) can name an ignored variable. When a third-party Desktop deployment names an OTLP endpoint in the environment it provides, that environment carries Desktop’s own `OTEL_RESOURCE_ATTRIBUTES`. ### Example configurations @@ -1194,7 +1194,7 @@ * `is_built_in`: Whether the subagent is a built-in agent type * `is_async`: Whether the subagent ran in the [background](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) * `total_tokens`: The token footprint of the subagent’s final API request: that one request’s input, cache creation, cache read, and output tokens, roughly the subagent’s context size at completion. Not a sum across the run - * `total_tool_uses`: Number of tool calls the subagent made across the whole run + * `total_tool_uses`: Number of tool calls the subagent made across the whole run, excluding [`SubagentHandback`](</docs/en/tools-reference>) * `duration_ms`: Run time in milliseconds * `model`: The model the subagent was resolved to run * `final_model`: The model that produced the subagent’s final response, which differs from `model` after a mid-run switch such as a fallback @@ -1220,7 +1220,7 @@ Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. Read `result` to see whether the sweep ran: * `"complete"`: the sweep ran, and the event carries its counts - * `"skipped"`: Claude Code couldn’t safely determine the retention period, so it paused the sweep and the event carries no counts. If `skip_reason` is `"settings_unknowable"` or `"settings_invalid_key_set"`, fix the settings error that `/status` reports on that machine so a later session can run the sweep + * `"skipped"`: Claude Code couldn’t safely determine the retention period, so it paused the sweep and the event carries no counts. If `skip_reason` is `"settings_unknowable"` or `"settings_invalid_key_set"`, fix any settings error that `/status` reports on that machine so a later session can run the sweep When [managed settings](</docs/en/server-managed-settings>) set `cleanupPeriodDays`, the managed value pins the retention period and the sweep runs even when a settings file in a lower-priority scope is broken or invalid. **Event Name** : `claude_code.retention_sweep` **Attributes** : @@ -1233,7 +1233,7 @@ * `used_default`: `"true"` when `period_days` fell back to `30`, `"false"` otherwise. On complete events, `"true"` means the 30-day default applied * `skip_reason`: Why Claude Code paused the sweep. Present only when `result` is `"skipped"`: * `"user_source_disabled"`: User settings are excluded, for example by the [`--setting-sources`](</docs/en/cli-reference#cli-flags>) flag or the SDK’s [`settingSources`](</docs/en/agent-sdk/typescript#options>) option, and no enabled source provides `cleanupPeriodDays` - * `"settings_unknowable"`: A settings file couldn’t be read or parsed, so `cleanupPeriodDays` or `desktopSessionCleanupPeriodDays` may be set to a value Claude Code can’t see + * `"settings_unknowable"`: A settings source couldn’t be read or parsed, so `cleanupPeriodDays` or `desktopSessionCleanupPeriodDays` may be set to a value Claude Code can’t see * `"settings_invalid_key_set"`: Settings have validation errors and `cleanupPeriodDays` or `desktopSessionCleanupPeriodDays` is explicitly set, so falling back to the default could delete or keep files against that setting * `"remote_settings_unknowable"`: A session in Claude Desktop’s Code tab on a third-party deployment requested [server-managed settings](</docs/en/server-managed-settings>). It received no usable response, so `cleanupPeriodDays` may be set to a value Claude Code can’t see * `transcripts_deleted`: Number of session transcripts, the top-level `~/.claude/projects/*/*.jsonl` files, that the sweep deleted
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -92,6 +92,7 @@ `OTEL_LOG_MANAGED_SETTINGS`| Add the redacted managed settings, and a SHA-256 digest of the settings before redaction, to managed settings resolved events (default: disabled). A value in project or local settings doesn’t turn it on. Requires Claude Code v2.1.274 or later| `1` to enable `OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). 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| `1` for inline bodies truncated at the content limit (60 KB by default), or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`| Content limit: the maximum length of content-bearing attributes such as model responses, tool content, system prompts, and raw API bodies, truncation marker included, in UTF-16 code units (default: 61440, i.e. 60 KB). The default is sized for backends that cap attribute values at 64 KB; raise it only if your backend accepts larger values, or lower it to cut telemetry volume. When an OpenTelemetry SDK attribute limit, `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` or one of its logrecord and span variants, is set lower, Claude Code truncates at that smaller value so the `[TRUNCATED ...]` marker stays within the SDK limit| `262144` +`OTEL_RESOURCE_INCLUDE_HOST`| Add the machine’s name and ID to the resource attributes of metrics, events, and traces (default: disabled). See Identify the machine a session ran on. Requires Claude Code v2.1.326 or later| `1` to enable `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes)| `900000` @@ -122,6 +123,37 @@ `OTEL_METRICS_INCLUDE_REPOSITORY`| Include `vcs.*` repository identity attributes on metrics and events. Requires Claude Code v2.1.269 or later| `false`| `true` Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. + +### Identify the machine a session ran on + +To see which machine each session ran on, set `OTEL_RESOURCE_INCLUDE_HOST=1` on Claude Code v2.1.326 or later. Set it under `env` in [managed settings](</docs/en/managed-settings>) or user settings, or in the shell you start `claude` from, not in [project or local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). The following example sets it in a settings file: + + { + "env": { + "OTEL_RESOURCE_INCLUDE_HOST": "1" + } + } + +The attributes `host.name` and `host.id` then appear in the resource block of metrics, events, and traces, not on metric datapoints: + + * `host.name`: the machine’s host name + * `host.id`: the operating system’s machine ID, not hashed. That’s the contents of `/etc/machine-id` on Linux, `IOPlatformUUID` on macOS, and the `MachineGuid` registry value on Windows. It’s left out when Claude Code can’t read one, for example in a container whose image has no machine ID. + +Both attributes name the machine that Claude Code runs on. In a Desktop SSH session that’s the remote machine, so set the variable there: see Attribute telemetry to Desktop SSH sessions. In a container, `host.name` is the container’s own host name, so to name the machine that runs the container, declare the name yourself in `OTEL_RESOURCE_ATTRIBUTES`. + +#### Troubleshoot missing host attributes + +If `host.name` and `host.id` are missing, check where and when you set `OTEL_RESOURCE_INCLUDE_HOST` and what started the session. Then check your exporter and endpoint variables and how your backend shows resource attributes: + + * **The session’s Claude Code is older than v2.1.326** : update it + * **You set the variable only in project or local settings** : set it in managed settings, user settings, or your shell. Run `/status` to see which variables Claude Code ignored. + * **The variable is`0` in a managed or user settings file**: if you set `1` [in your shell or in a lower-precedence file](</docs/en/settings-reference#how-env-values-interact-with-your-shell>), the `0` still applies. Change the `0`, or ask your administrator if it’s in managed settings. + * **You set the variable after the session started** : start a new session, because Claude Code reads it once at startup + * **The desktop app started the session** : a local session gets some variables from your shell profile, but not this one, so set it in managed or user settings. For a Desktop SSH session, set it on the remote machine: see Attribute telemetry to Desktop SSH sessions. + * **The session is a cloud session in an Anthropic-hosted environment** : the attributes aren’t added there. To tell cloud sessions apart, see Attribute telemetry to cloud sessions. + * **Any exporter variable lists`console`**: remove `console` from `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and `OTEL_TRACES_EXPORTER`, and the attributes arrive at your other exporters + * **A per-signal endpoint variable, such as`OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`, isn’t a URL**: write a bare `10.0.0.1:4317` as a URL, such as `http://10.0.0.1:4317` + * **Your metrics backend doesn’t surface resource attributes** : with the `prometheus` exporter, look for the `host_name` and `host_id` labels of the `target_info` metric. Otherwise, look in the resource block of events and traces, or declare the name yourself in `OTEL_RESOURCE_ATTRIBUTES`, which by default also reaches metric datapoints. ### Traces (beta) @@ -360,7 +392,11 @@ ### Attribute telemetry to Desktop SSH sessions -To see which remote machine a [Desktop SSH session](</docs/en/desktop#ssh-sessions>) ran on, name each machine in a custom attribute. Metrics and events don’t name the machine a session ran on. On each remote machine, add `OTEL_RESOURCE_ATTRIBUTES` to the `env` block that turns telemetry on, in the [managed settings file the session reads](</docs/en/desktop#managed-settings>). Write the name out in each machine’s file. Claude Code doesn’t expand the value, so `host.name=$(hostname)` arrives as those characters. The following example names the machine `build-7`: +To see which remote machine a [Desktop SSH session](</docs/en/desktop#ssh-sessions>) ran on, either set `OTEL_RESOURCE_INCLUDE_HOST=1` or name each machine in a custom attribute. Choose the custom attribute if you need the name on metric datapoints: with `OTEL_RESOURCE_INCLUDE_HOST=1`, `host.name` appears in the resource block only. Set `OTEL_RESOURCE_INCLUDE_HOST` on the remote machine, in the `env` block that turns telemetry on, in the [managed settings file the session reads](</docs/en/desktop#managed-settings>). The [copy of Claude Code that the session runs](</docs/en/desktop#files-and-processes-on-the-remote-machine>) must be v2.1.326 or later. If `host.name` and `host.id` don’t arrive, see Troubleshoot missing host attributes. + +#### Name each remote machine in a custom attribute + +On each remote machine, add `OTEL_RESOURCE_ATTRIBUTES` to the `env` block that turns telemetry on, in the [managed settings file the session reads](</docs/en/desktop#managed-settings>). Write the name out in each machine’s file. Claude Code doesn’t expand the value, so `host.name=$(hostname)` arrives as those characters. The following example names the machine `build-7`: { "env": { @@ -373,7 +409,7 @@ } } -When nothing else sets the variable, `host.name` arrives in the resource block, in Desktop SSH sessions and in the CLI on that machine. For where else custom attributes appear, see Multi-team organization support. If the name doesn’t arrive, check for one of these causes: +`host.name` arrives in the resource block and, by default, on metric datapoints and events. Desktop SSH sessions and the CLI on that machine both send it. To keep it off datapoints, see Multi-team organization support. If the name that you set in `OTEL_RESOURCE_ATTRIBUTES` doesn’t arrive, check for one of these causes: * **You set it on the computer that runs Desktop** : Desktop doesn’t pass a value you set there to the SSH session * **You exported it in`/etc/profile` or another file that only login shells read**: the name arrives when you run `claude` from a login shell, but not in a Desktop SSH session. Desktop doesn’t start Claude Code through a login shell. Set the variable under `env` in the [managed settings file](</docs/en/desktop#managed-settings>) on the remote machine instead. @@ -1240,7 +1276,7 @@ * `managed_settings.helper.applied`: `"output"` while the helper’s own output serves as the managed settings, `"none"` when it doesn’t * `managed_settings.helper.entry`: `"policyHelper"` when Claude Code selected a [`policyHelper`](</docs/en/settings-reference#policyhelper>). Absent when it selected no helper * `managed_settings.helper.path`: the helper’s configured [`path`](</docs/en/settings-reference#policyhelper-path>). Present whenever Claude Code selected a helper, whether or not `OTEL_LOG_MANAGED_SETTINGS` is set - * `managed_settings.resolved_sha256` (when `OTEL_LOG_MANAGED_SETTINGS=1`): SHA-256 of the resolved managed settings before redaction, serialized as JSON with keys sorted recursively and no whitespace. Machines with the same digest run the same policy. Claude Code sends the digest only with the opt-in because a short policy can be recovered by hashing guesses. Absent when no managed settings resolved, and on `refused` events + * `managed_settings.resolved_sha256` (when `OTEL_LOG_MANAGED_SETTINGS=1`): SHA-256 of the resolved managed settings before redaction, serialized as JSON with keys sorted recursively and no whitespace. Machines with the same digest resolved the same managed settings. The event carries the digest only with the opt-in because a short policy can be recovered by hashing guesses. Absent when no managed settings resolved, and on `refused` events * `managed_settings.settings` (when `OTEL_LOG_MANAGED_SETTINGS=1`): the names and shape of the resolved managed settings as a JSON string, with the values redacted. Absent on `refused` events. Claude Code builds it from its settings schema: * A setting name the schema declares is exported, and a key it doesn’t declare is left out * Booleans, numbers, and string values the schema restricts to a fixed set of options, such as `permissions.defaultMode`, are exported as-is. `sandbox.network.httpProxyPort` and `sandbox.network.socksProxyPort` are exported as `"[REDACTED]"` @@ -1463,6 +1499,7 @@ * `os.type`: Operating system type (for example, `linux`, `darwin`, `windows`) * `os.version`: Operating system version string * `host.arch`: Host architecture (for example, `amd64`, `arm64`) + * `host.name`, `host.id`: The machine’s name and ID, off by default. See Identify the machine a session ran on. * `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux) * Meter Name: `com.anthropic.claude_code` @@ -1501,6 +1538,7 @@ * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES` in your shell, user settings, or managed settings. It’s ignored in [project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). The bodies contain the full conversation history, including the system prompt, every prior user and assistant turn, and tool results, so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude Code always redacts Claude’s extended-thinking content from these bodies, regardless of other settings. The value you set determines how Claude Code delivers the bodies: * With `=1`, Claude Code emits `api_request_body` and `api_response_body` log events for each API call. The events’ `body` attribute carries the JSON-serialized payload, truncated at the content limit (60 KB by default) * With `=file:<dir>`, Claude Code writes untruncated bodies to `.request.json` and `.response.json` files under that directory, and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. For each successful response, Claude Code also appends one line to `index.jsonl` in that directory, linking the response file to the request file that produced it and to the transcript message it became. Each line holds no message content, and the API response body event section lists its fields. The index file requires Claude Code v2.1.274 or later + * The machine’s name and ID aren’t included by default. To include them as `host.name` and `host.id`, set `OTEL_RESOURCE_INCLUDE_HOST=1`. A host name often contains a person’s name, and `host.id` is a lasting identifier for the machine. If you set the variable in managed settings, tell the people who use those machines, because Claude Code shows them no notice. ## Monitor Claude Code on Amazon Bedrock
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -815,10 +815,10 @@ * Claude Code approved the call in auto mode without asking the classifier * The user answered the prompt Claude Code showed after [repeated blocks](</docs/en/permission-modes#repeated-block-thresholds>) * In a `-p` run without `--permission-prompt-tool`, Claude Code denied the call after repeated blocks because there was nobody to answer a prompt. That event reports `decision` as `"reject"` and `source` as `"config"` - * `classifier_category` (when `OTEL_LOG_TOOL_DETAILS=1`): The name of the [built-in rule](</docs/en/auto-mode-config#inspect-the-defaults-and-your-effective-config>) the classifier named when it blocked the call, in lowercase with underscores, such as `"data_exfiltration"` for the Data Exfiltration rule. Requires Claude Code v2.1.301 or later. The attribute is present when both of these hold: + * `classifier_category` (when `OTEL_LOG_TOOL_DETAILS=1`): The name of the [policy](</docs/en/auto-mode-config#fix-a-policy-denial>) or [built-in rule](</docs/en/auto-mode-config#inspect-the-defaults-and-your-effective-config>) the classifier named when it blocked the call, in lowercase with underscores, such as `"data_exfiltration"` for the Data Exfiltration rule. Requires Claude Code v2.1.301 or later. The attribute is present when both of these hold: * `classifier_verdict` is `"block"` - * The classifier named exactly one rule, and that rule is a built-in one rather than one you wrote -Before v2.1.302, the attribute was also absent on any block that [server-side classifier review](</docs/en/permission-modes#server-side-classifier-review>) decided. + * The classifier gave exactly one name, and Claude Code recognizes it as a policy or a built-in rule +Before v2.1.302, the attribute was also absent on any block that [server-side classifier review](</docs/en/permission-modes#server-side-classifier-review>) decided. Before v2.1.323, it was absent on blocks that named a policy. * `permission_mode`: [Permission mode](</docs/en/permission-modes>) active when this call’s permission check began: `"default"`, `"plan"`, `"acceptEdits"`, `"bypassPermissions"`, `"dontAsk"`, or `"auto"`. Manual mode appears as `"default"`. A [subagent](</docs/en/sub-agents#permission-modes>) call reports the subagent’s permission mode rather than the session’s. Requires Claude Code v2.1.301 or later * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters. Same shape as the Tool result event, minus post-execution fields such as `git_commit_id`. Values may differ from `tool_result` for an accepted call if the permission decision rewrites the tool input via `updatedInput`. Use this attribute to see which command was rejected when `decision` is `"reject"`. * For `"sdk_host_builtin_mcp"` tools: `mcp_server_name` and `mcp_tool_name` are included even when `OTEL_LOG_TOOL_DETAILS` is off, because the host application defines these names; without them, a rejected call to one of these built-in servers would be unattributable on the default stream. For user-configured MCP servers, the event’s `tool_name` is always the literal `"mcp_tool"`, and the server and tool names appear only in `tool_parameters` with the flag on; argument content requires the flag everywhere. @@ -865,7 +865,7 @@ * `rule_source`: Settings source of the rule involved, such as `"policySettings"`, `"userSettings"`, `"projectSettings"`, `"localSettings"`, `"flagSettings"`, `"cliArg"`, or `"session"` * `grant_scope`: `"once"` or `"session"` for a prompt approved without saving a rule to a settings file * `circuit_breaker`: The built-in safety check, such as `"dangerousRemoval"`, `"outsideReadsBlocked"`, or `"claudeSettingsFile"` - * `classifier_category`: With `OTEL_LOG_TOOL_DETAILS=1`, the [built-in rule](</docs/en/auto-mode-config#inspect-the-defaults-and-your-effective-config>) behind an auto mode block, such as `"data_exfiltration"` + * `classifier_category`: With `OTEL_LOG_TOOL_DETAILS=1`, the [built-in rule](</docs/en/auto-mode-config#inspect-the-defaults-and-your-effective-config>) behind an auto mode block, such as `"data_exfiltration"`, under the same conditions as on `tool_decision` * `hook_event`: `"pre_tool_use"` for a `PreToolUse` hook, or `"post_tool_use"`, `"post_tool_use_failure"`, `"stop"`, or `"subagent_stop"` on `"hook_review"` events * `tool_class`: `"bash"` for Bash and [Monitor](</docs/en/tools-reference#monitor-tool>), `"powershell"`, `"file"` for Read, Edit, Write, NotebookEdit, Glob, and Grep, `"web"` for WebFetch and WebSearch, `"mcp"`, or `"other"` * `tool_name`: The tool’s name, such as `"Bash"` for a built-in tool, or `"mcp_tool"`, `"skill_tool"`, `"dynamic_tool"`, or `"other_tool"`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -356,7 +356,7 @@ export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization" -Wrapping values in quotes doesn’t escape spaces. For example, `org.name="My Company"` results in the literal value `"My Company"` with the quotes included, not `My Company`. +Wrapping values in quotes doesn’t escape spaces. ### Attribute telemetry to Desktop SSH sessions
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -696,7 +696,7 @@ * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. - * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. + * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. When a [mod](</docs/en/plugins/mods/overview>) from outside the official marketplace and built-in bundle calls [`$.model`](</docs/en/plugins/mods/api#call-a-model>), `marketplace.name` is also present, redacted to `"third-party"` unless you set `OTEL_LOG_TOOL_DETAILS=1`. #### API error event @@ -716,7 +716,7 @@ * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. - * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. + * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. For `marketplace.name` on a mod’s `$.model` calls, see `api_request`. #### API refusal event
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -74,7 +74,7 @@ `CLAUDE_CODE_ENABLE_TELEMETRY`| Enables telemetry collection (required)| `1` `OTEL_METRICS_EXPORTER`| Metrics exporter types, comma-separated. Use `none` to disable| `console`, `otlp`, `prometheus`, `none` `OTEL_LOGS_EXPORTER`| Logs/events exporter types, comma-separated. Use `none` to disable| `console`, `otlp`, `none` -`OTEL_EXPORTER_OTLP_PROTOCOL`| Protocol for OTLP exporter, applies to all signals. Claude Code has no default protocol, so set this or the signal-specific protocol variable for each `otlp` exporter you enable| `grpc`, `http/json`, `http/protobuf` +`OTEL_EXPORTER_OTLP_PROTOCOL`| Protocol for OTLP exporter, applies to all signals. Defaults to `http/protobuf` for a valid `http://` or `https://` endpoint. For a gRPC endpoint such as `http://localhost:4317`, set this to `grpc`. The default requires Claude Code v2.1.323 or later| `grpc`, `http/json`, `http/protobuf` `OTEL_EXPORTER_OTLP_ENDPOINT`| OTLP collector endpoint for all signals| `http://localhost:4317` `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL`| Protocol for metrics, overrides general setting| `grpc`, `http/json`, `http/protobuf` `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`| OTLP metrics endpoint, overrides general setting| `http://localhost:4318/v1/metrics` @@ -377,8 +377,8 @@ * **You set it on the computer that runs Desktop** : Desktop doesn’t pass a value you set there to the SSH session * **You exported it in`/etc/profile` or another file that only login shells read**: the name arrives when you run `claude` from a login shell, but not in a Desktop SSH session. Desktop doesn’t start Claude Code through a login shell. Set the variable under `env` in the [managed settings file](</docs/en/desktop#managed-settings>) on the remote machine instead. - * **A value has a space inside it** : Claude Code then copies none of the keys onto events or datapoints and reports no error. Take the space out of the value. - * **Something else already sets the variable** : in a session that the desktop app starts, a variable already set in the launch environment [takes precedence over settings files](</docs/en/settings-reference#how-env-values-interact-with-your-shell>). The [debug log](</docs/en/debug-your-config>) names each ignored variable. When a third-party Desktop deployment names an OTLP endpoint in the environment it provides, that environment carries Desktop’s own `OTEL_RESOURCE_ATTRIBUTES`. + * **A value has a space inside it** : Claude Code then copies none of the keys onto events or datapoints. To see which value has the space, run `/status` in a session on the remote machine. Take the space out of the value. + * **Something else already sets the variable** : in a session that the desktop app starts, a variable already set in the launch environment [takes precedence over settings files](</docs/en/settings-reference#how-env-values-interact-with-your-shell>). The [debug log](</docs/en/debug-your-config>) can name an ignored variable. When a third-party Desktop deployment names an OTLP endpoint in the environment it provides, that environment carries Desktop’s own `OTEL_RESOURCE_ATTRIBUTES`. ### Example configurations @@ -553,12 +553,12 @@ * All standard attributes * `model`: Model identifier (for example, “claude-sonnet-5”) - * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` + * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, `"auxiliary"`, `"plugin_model_complete"`, or `"plugin_model_classify"`. The last two mark the requests a [mod](</docs/en/plugins/mods/overview>) makes with `$.model.complete` or `$.model.classify`. Claude Code counts those requests from v2.1.324, so totals can step up after you upgrade. * `speed`: `"fast"` when the request used fast mode. Absent otherwise * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. * `agent.name`: Subagent type that issued the request. Built-in agent names and agents from official-marketplace plugins appear verbatim. Other user-defined agent names are replaced with `"custom"`. Absent when the request was not issued by a named subagent type. * `skill.name`: Skill active for the request, set by the Skill tool or a `/` command, or inherited by a spawned subagent. Built-in, bundled, user-defined, and official-marketplace plugin skill names appear verbatim. Third-party plugin skill names are replaced with `"third-party"`. Absent when no skill is active. - * `plugin.name`: Owning plugin when the active skill or subagent is provided by a plugin. Official-marketplace plugin names appear verbatim. Third-party plugin names are replaced with `"third-party"`. Absent when neither the skill nor the subagent has an owning plugin. + * `plugin.name`: Owning plugin when the active skill or subagent is provided by a plugin, or the plugin whose `$.model` call made the request. Official-marketplace plugin names appear verbatim. Third-party plugin names are replaced with `"third-party"`. Absent for other requests. * `marketplace.name`: Marketplace the owning plugin was installed from. Only emitted for official-marketplace plugins, even with `OTEL_LOG_TOOL_DETAILS=1` set. Absent otherwise. * `mcp_server.name`: MCP server whose tool result this request consumed. Built-in, claude.ai-proxied, and official-registry server names appear verbatim. User-configured server names are replaced with `"custom"`. Absent when the request consumed no MCP tool result. Before v2.1.222, Claude Code set this attribute on every request after an MCP tool call, not only on requests that consumed a tool result, so dashboards that aggregate it show a step down after you upgrade. * From v2.1.312, the name of a remote server with a fixed URL that a plugin from Anthropic’s official marketplace declares also appears verbatim, as `plugin_<plugin>_<server>`. That name is replaced with `"custom"` when the plugin’s marketplace copy didn’t come from Anthropic’s registered source, such as one mounted from a seed directory in a cloud session. @@ -571,7 +571,7 @@ * All standard attributes * `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`). The `"input"` type excludes tokens read from or written to the prompt cache, which are counted under `"cacheRead"` and `"cacheCreation"`. The `"cacheCreation"` type counts cache writes with the five-minute and one-hour [cache lifetimes](</docs/en/prompt-caching#cache-lifetime>) together. * `model`: Model identifier (for example, “claude-sonnet-5”) - * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` + * `query_source`: Category of the subsystem that issued the request. See Cost counter for the values. * `speed`: `"fast"` when the request used fast mode. Absent otherwise * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. See Cost counter for details. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior.
modified
Show diff (1044 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -2,11 +2,7 @@ For the Claude API or Managed Agents, see [OpenTelemetry for the Claude API](<https://platform.claude.com/docs/en/manage-claude/opentelemetry>). -## - -​ - -Quick start +## Quick start Configure OpenTelemetry using environment variables: @@ -33,11 +29,7 @@ To verify a setup that exports metrics, check your backend for the `claude_code.session.count` metric, which Claude Code emits when a session starts. To verify a logs-only setup, submit a prompt and check for the `claude_code.user_prompt` event. If nothing arrives, start Claude Code with `claude --debug-file <path>` and check the log it writes to that path. Claude Code reports failures from the exporters you configure as `[3P telemetry]` errors, where 3P means third-party. Lines prefixed `[Anthropic telemetry]` describe [Anthropic’s separate operational telemetry](</docs/en/data-usage#telemetry-services>) and don’t indicate a problem with your setup. For full configuration options, see the [OpenTelemetry specification](<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options>). -## - -​ - -Administrator configuration +## Administrator configuration Administrators can configure OpenTelemetry settings for all users through the [managed settings file](</docs/en/managed-settings#delivery-mechanisms>). See the [settings precedence](</docs/en/settings#settings-precedence>) for more information about how settings are applied. Example managed settings configuration: @@ -54,11 +46,7 @@ In the Claude Desktop app, Code tab sessions read these managed settings from the sources that [reach each kind of Desktop session](</docs/en/desktop#managed-settings>). The OpenTelemetry form for Cowork under **Monitoring** in the admin console’s [Data and privacy settings](<https://claude.ai/admin-settings/data-privacy-controls>) applies to Cowork sessions only, so neither the terminal CLI nor the Code tab exports to a collector you set there. Claude Code ignores the [OpenTelemetry exporter variables](</docs/en/settings-reference#variables-claude-code-ignores-in-env>) in a repository’s `.claude/settings.json` and `.claude/settings.local.json`, so a repository can’t use them to turn telemetry on, choose where it goes, or capture content. Set them in managed settings, or have each developer set them in their shell or `~/.claude/settings.json`. A repository can still turn a signal off by setting its exporter selector, such as `OTEL_LOGS_EXPORTER`, to `none`, unless managed settings, a `--settings` file, or the environment you start Claude Code from sets that variable. Claude Code doesn’t pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool doesn’t inherit Claude Code’s exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry. -### - -​ - -How managed settings lock the OTLP destination +### How managed settings lock the OTLP destination When you set an `OTEL_EXPORTER_OTLP_*` variable in managed settings, Claude Code removes conflicting developer-set variables at startup and logs a warning in the debug log. What it removes depends on which variable you set: @@ -75,17 +63,9 @@ Claude Code doesn’t remove per-signal variables that you set in managed settings itself, so you can route one signal to a different collector by setting its variable there, as the SIEM example does. If you set a per-signal credential there, Claude Code removes the developer-set endpoint for that signal. This removal behavior changes where telemetry is delivered, not what Claude Code collects. Before v2.1.217, every variable followed per-key settings precedence independently, so a signal-specific endpoint set in user settings or the shell redirected that signal away from the managed collector. When the desktop app or a [self-hosted environment](</docs/en/self-hosted-environments>) runner launches Claude Code and names an OTLP endpoint in the environment it provides, Claude Code pins the destination the same way: the launcher’s telemetry variables remove developer-set variables exactly as managed settings do. Claude Code doesn’t remove variables that the launcher itself set. Requires Claude Code v2.1.251 or later. -## - -​ - -Configuration details - -### - -​ - -Common configuration variables +## Configuration details + +### Common configuration variables These variables configure exporters, endpoints, and export behavior for all deployments. If you set a per-signal endpoint or protocol variable, such as `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`, Claude Code uses it instead of the generic variable for that signal. If you set a per-signal headers variable, such as `OTEL_EXPORTER_OTLP_METRICS_HEADERS`, Claude Code merges it with the generic `OTEL_EXPORTER_OTLP_HEADERS` for that signal. On machines with managed settings, see How managed settings lock the OTLP destination for what Claude Code removes. @@ -117,11 +97,7 @@ For the `http/protobuf` and `http/json` protocols, Claude Code sends each export request with a `Content-Length` header. -### - -​ - -mTLS authentication +### mTLS authentication How you configure client certificates for the OTLP exporter depends on the OTLP protocol in use for that signal, set via `OTEL_EXPORTER_OTLP_PROTOCOL` or the per-signal override. The same configuration applies to metrics, logs, and traces. @@ -132,11 +108,7 @@ For `grpc`, the OpenTelemetry SDK reads the standard OTLP variables directly, so existing configurations that set the per-signal metrics variables continue to work. On machines with managed settings, Claude Code may remove developer-set per-signal credentials and endpoints at startup. -### - -​ - -Metrics cardinality control +### Metrics cardinality control The following environment variables control which attributes are included in metrics and events to manage cardinality: @@ -151,11 +123,7 @@ Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. -### - -​ - -Traces (beta) +### Traces (beta) Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend. Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the common OTLP configuration for endpoint, protocol, headers, and mTLS. On machines with managed settings, Claude Code may remove developer-set per-signal credentials and endpoints at startup. @@ -170,11 +138,7 @@ Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. When tracing is active and Claude Code is connected directly to the Anthropic API, each model request carries a W3C `traceparent` header set to the `claude_code.llm_request` span’s context, and the API’s `traceresponse` header is recorded as a span link. Together these connect Claude Code’s client-side spans to the server-side trace through any compliant intermediary. Outbound HTTP MCP requests carry `traceparent` the same way. The header is not sent to third-party providers. By default, the `traceparent` header on model and HTTP MCP requests is sent only when `ANTHROPIC_BASE_URL` is unset or points at the Anthropic API, since some proxies reject unrecognized headers. The subprocess `TRACEPARENT` variable is controlled by the same switch for consistency. If you run Claude Code through a custom `ANTHROPIC_BASE_URL` proxy and want trace context propagated, set `CLAUDE_CODE_PROPAGATE_TRACEPARENT=1`. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. The inbound trace context also applies to events. In Agent SDK and `-p` sessions with `TRACEPARENT` set, each OTLP event log record carries `trace_id` and `span_id` values that join it to your application’s trace, even when the traces exporter isn’t configured, so your logging backend can correlate events with the rest of the trace. A record emitted while an interaction is active carries the interaction span’s IDs, even when Claude Code emits it outside the span’s async context, such as in a permission prompt callback or for a record buffered during startup and exported later. A record emitted with no active interaction span carries the inbound `TRACEPARENT` IDs directly. -#### - -​ - -Span hierarchy +#### Span hierarchy Each user prompt starts a `claude_code.interaction` root span. API calls, tool calls, and hook executions are recorded as its children. Tool spans have two child spans of their own: one for the time spent waiting on a permission decision and one for the execution itself. When the Agent tool, or legacy Task tool, spawns a subagent, the subagent’s API and tool spans nest under the parent’s `claude_code.tool` span. @@ -188,11 +152,7 @@ In Agent SDK and `claude -p` sessions, `claude_code.interaction` itself becomes a child of the caller’s span when `TRACEPARENT` is set in the environment. When a `PreToolUse` hook [defers a tool call](</docs/en/hooks#defer-a-tool-call-for-later>), Claude Code saves the trace context of the turn that deferred it. When you resume the session and the tool re-runs, the tool’s spans join that earlier turn’s trace as children of the turn’s `claude_code.interaction` span. -#### - -​ - -Span attributes +#### Span attributes Every span carries the standard attributes plus a `span.type` attribute matching its name. The tables below list the additional attributes set on each span. The `llm_request`, `tool.execution`, and `hook` spans set OpenTelemetry status `ERROR` when they record a failure; the other spans always end with status `UNSET`. **`claude_code.interaction`** @@ -331,19 +291,11 @@ Under detailed beta tracing with `OTEL_LOG_USER_PROMPTS=1`, Claude Code also emits a `claude_code.system_prompt` event that carries the complete system prompt, truncated at the content limit. It arrives the first time a session sends each distinct system prompt, and again after compaction. -### - -​ - -Dynamic headers +### Dynamic headers For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically. Dynamic headers apply only to the `http/protobuf` and `http/json` protocols. With the `grpc` protocol, Claude Code uses only the static headers variables, `OTEL_EXPORTER_OTLP_HEADERS` and its per-signal variants. -#### - -​ - -Settings configuration +#### Settings configuration Add to your `.claude/settings.json`, replacing the path with your own script: @@ -353,11 +305,7 @@ The value can be the path to an executable file, including a path that contains spaces, or a shell command line with arguments. On Windows, the value always runs through the shell, so quote a path that contains spaces inside the JSON value. -#### - -​ - -Script requirements +#### Script requirements The script must output valid JSON with string key-value pairs representing HTTP headers: @@ -372,19 +320,11 @@ * The debug log, when running with [`--debug`](</docs/en/cli-reference#cli-flags>) or after running `/debug` in the session * stderr, in non-interactive sessions started with `-p` -#### - -​ - -Refresh behavior +#### Refresh behavior The headers helper script runs at startup and periodically thereafter to support token refresh. By default, the script runs every 29 minutes. Customize the interval with the `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` environment variable. -### - -​ - -Multi-team organization support +### Multi-team organization support Organizations with multiple teams or departments can add custom attributes to distinguish between different groups using the `OTEL_RESOURCE_ATTRIBUTES` environment variable: @@ -405,7 +345,7 @@ * **No spaces allowed** : values can’t contain spaces. For example, `user.organizationName=My Company` is invalid * **Format** : must be comma-separated key=value pairs: `key1=value1,key2=value2` * **Allowed characters** : only US-ASCII characters excluding control characters, whitespace, double quotes, commas, semicolons, and backslashes - * **Special characters** : characters outside the allowed range must be percent-encoded + * **Special characters** : characters outside the allowed range must be percent-encoded, and an `=` inside a value must be written as `%3D` For a value that would need a space, use underscores or camelCase instead. The following examples set `org.name` with each form: @@ -418,11 +358,7 @@ Wrapping values in quotes doesn’t escape spaces. For example, `org.name="My Company"` results in the literal value `"My Company"` with the quotes included, not `My Company`. -### - -​ - -Attribute telemetry to Desktop SSH sessions +### Attribute telemetry to Desktop SSH sessions To see which remote machine a [Desktop SSH session](</docs/en/desktop#ssh-sessions>) ran on, name each machine in a custom attribute. Metrics and events don’t name the machine a session ran on. On each remote machine, add `OTEL_RESOURCE_ATTRIBUTES` to the `env` block that turns telemetry on, in the [managed settings file the session reads](</docs/en/desktop#managed-settings>). Write the name out in each machine’s file. Claude Code doesn’t expand the value, so `host.name=$(hostname)` arrives as those characters. The following example names the machine `build-7`: @@ -444,11 +380,7 @@ * **A value has a space inside it** : Claude Code then copies none of the keys onto events or datapoints and reports no error. Take the space out of the value. * **Something else already sets the variable** : in a session that the desktop app starts, a variable already set in the launch environment [takes precedence over settings files](</docs/en/settings-reference#how-env-values-interact-with-your-shell>). The [debug log](</docs/en/debug-your-config>) names each ignored variable. When a third-party Desktop deployment names an OTLP endpoint in the environment it provides, that environment carries Desktop’s own `OTEL_RESOURCE_ATTRIBUTES`. -### - -​ - -Example configurations +### Example configurations Set these environment variables before running `claude`. Each scenario below shows a complete configuration, and each variable is described under Common configuration variables. To confirm a configuration took effect, check your backend for the `claude_code.session.count` metric after starting a session; the Quick start covers logs-only verification and what to check when nothing arrives. For console debugging with a 1-second export interval: @@ -498,11 +430,7 @@ export OTEL_EXPORTER_OTLP_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 -## - -​ - -Telemetry from cloud sessions and Claude Tag +## Telemetry from cloud sessions and Claude Tag [Cloud sessions](</docs/en/claude-code-on-the-web>), including [Claude Tag](<https://claude.com/docs/claude-tag/overview>) channel sessions, run in [cloud environments](</docs/en/cloud-environments>) rather than on your users’ devices, so a managed settings file or shell profile on those devices doesn’t configure their telemetry. For sessions in Anthropic-hosted environments, this section covers where to set the telemetry variables, how to make your collector reachable from the environment, and how to tell cloud and Claude Tag sessions apart in the exported data. To export telemetry from those sessions, set `CLAUDE_CODE_ENABLE_TELEMETRY` and the `OTEL_*` variables, using the same keys as the administrator configuration example, in one of two places: @@ -515,11 +443,7 @@ * **Claude Tag channels** : make the allowlist and any environment-variable changes on the [shared environment](</docs/en/cloud-environments#organization-shared-environments>) set as your organization’s default or pinned to the channel. * **Cowork is configured separately** : Cowork sessions don’t receive server-managed settings, as the [surface coverage table](</docs/en/model-config#surface-coverage>) shows, so the server-managed `env` block doesn’t configure their telemetry. -### - -​ - -Attribute telemetry to cloud sessions +### Attribute telemetry to cloud sessions By default, metrics and events from a cloud session carry the standard attributes, including `session.id`, `ccr.session.id`, and `organization.id`, so you can filter by session or organization without extra configuration. The `ccr.session.id` value is the session’s `CLAUDE_CODE_REMOTE_SESSION_ID`. To turn it into the session’s transcript URL, see [Link output back to the session](</docs/en/cloud-environments#link-output-back-to-the-session>). To tell cloud sessions apart, group or filter on `ccr.session.id`, not `session.id`. To attribute telemetry in more detail, use these options: @@ -528,17 +452,9 @@ In Claude Tag channel sessions, Claude works as your organization’s [shared identity](</docs/en/cloud-environments#set-the-environment-a-claude-tag-channel-uses>) rather than as any member, so don’t rely on the `user.*` attributes to identify who tagged Claude. -## - -​ - -Available metrics and events - -### - -​ - -Standard attributes +## Available metrics and events + +### Standard attributes All metrics and events share these standard attributes: @@ -570,11 +486,7 @@ * `agent_id`: identifier of the [subagent](</docs/en/sub-agents>) that raised the event, such as `a3f2c1b4d5e6f7a80`. Events that carry it include a subagent’s API and tool events, its `assistant_response` events, and `subagent_completed` for the finished subagent. Absent on main-session and [in-process teammate](</docs/en/agent-teams#choose-a-display-mode>) events. The subagent’s span `agent_id` is the same value, or adds a label after the leading `a` as in `acompact-3f2c1b4d5e6f7a80`. Requires Claude Code v2.1.310 or later * `parent_agent_id`: the `agent_id` of the agent that spawned or last resumed the subagent that raised the event. Absent when that agent is the main session. Requires Claude Code v2.1.310 or later -#### - -​ - -Repository attributes +#### Repository attributes Set `OTEL_METRICS_INCLUDE_REPOSITORY=true` to tag metrics and events with the identity of the session’s repository, so a shared collector can attribute usage per repository. Requires Claude Code v2.1.269 or later. Claude Code derives these attributes once per session from the repository’s `origin` remote. When the HTTPS and SSH remotes of a repository name the same host and the same path, as they do on GitHub, GitLab, and Bitbucket Cloud, both produce identical values: @@ -587,11 +499,7 @@ Values are lowercased, and credentials, query strings, and fragments from the remote URL never appear in them. The attributes are omitted when the session has no `origin` remote, when the remote isn’t URL-shaped, or when the only enclosing repository is your home directory. To get these attributes from a [cloud session](</docs/en/claude-code-on-the-web>), set the telemetry variables, including `OTEL_METRICS_INCLUDE_REPOSITORY`, on its [cloud environment](</docs/en/cloud-environments#set-environment-variables>). Also allow your collector’s domain in the environment’s [network access](</docs/en/cloud-environments#network-access>). A `vcs.*` key you declare in `OTEL_RESOURCE_ATTRIBUTES` replaces the derived value for that key. If you declare `vcs.repository.url.full`, Claude Code never reads the remote and reports only the keys you declare. If HTTPS and SSH clones of one repository report different values, such as on a self-hosted install whose HTTPS clone URL carries a path prefix the SSH URL lacks, declare `vcs.repository.url.full` in `OTEL_RESOURCE_ATTRIBUTES` along with every other `vcs.*` key you want reported. Every clone then reports the identity you declare. The attributes flow only to your own exporters; Anthropic’s telemetry drops every `vcs.*` key. -### - -​ - -Metrics +### Metrics Claude Code exports the following metrics. The Unit column shows the OpenTelemetry unit string attached to each metric; count metrics carry none. @@ -608,30 +516,18 @@ When `prometheus` is the only exporter listed in `OTEL_METRICS_EXPORTER`, Claude Code omits the `USD`, `tokens`, and `s` units from the exported metrics so the scrape stays valid Prometheus text format. Metric names don’t change, and configurations that combine exporters, such as `otlp,prometheus`, keep the units. -### - -​ - -Metric details +### Metric details Each metric includes the standard attributes listed above. Metrics with additional context-specific attributes are noted below. -#### - -​ - -Session counter +#### Session counter Incremented at the start of each session. To count people instead, see Usage monitoring. **Attributes** : * All standard attributes * `start_type`: How the session was started. One of `"fresh"`, `"resume"`, `"continue"`, or `"agents_view"`. The `"agents_view"` value identifies the `claude agents` dashboard process, a user-launched local UI rather than a conversational session. Filter on this value to separate UI process launches from conversational sessions in your dashboards. -#### - -​ - -Lines of code counter +#### Lines of code counter Incremented when code is added or removed. **Attributes** : @@ -639,31 +535,19 @@ * `type`: (`"added"`, `"removed"`) * `model`: Model identifier for the model that made the change (for example, “claude-sonnet-5”) -#### - -​ - -Pull request counter +#### Pull request counter Incremented when Claude Code creates a pull request or merge request through a shell command or an MCP tool. **Attributes** : * All standard attributes -#### - -​ - -Commit counter +#### Commit counter Incremented when creating git commits via Claude Code. **Attributes** : * All standard attributes -#### - -​ - -Cost counter +#### Cost counter Incremented after each API request. The `agent.name`, `skill.name`, `plugin.name`, `mcp_server.name`, and `mcp_tool.name` attributes each redact some names to a `"custom"` or `"third-party"` placeholder by default. If you set `OTEL_LOG_TOOL_DETAILS=1`, they carry the real names instead. Before v2.1.273, the cost and token counters and the `api_request`, `api_error`, and `api_refusal` events carried the redacted values even with `OTEL_LOG_TOOL_DETAILS=1` set. **Attributes** : @@ -680,11 +564,7 @@ * From v2.1.312, the name of a remote server with a fixed URL that a plugin from Anthropic’s official marketplace declares also appears verbatim, as `plugin_<plugin>_<server>`. That name is replaced with `"custom"` when the plugin’s marketplace copy didn’t come from Anthropic’s registered source, such as one mounted from a seed directory in a cloud session. * `mcp_tool.name`: MCP tool whose result this request consumed, with the same redaction and version behavior as `mcp_server.name`, except that it can read `"custom"` when `mcp_server.name` shows a `plugin_<plugin>_<server>` name. Absent when the request consumed no MCP tool result. -#### - -​ - -Token counter +#### Token counter Incremented after each API request. **Attributes** : @@ -696,11 +576,7 @@ * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. See Cost counter for details. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. -#### - -​ - -Code edit tool decision counter +#### Code edit tool decision counter Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage. **Attributes** : @@ -710,30 +586,18 @@ * `source`: Where the decision came from. One of `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`. See the Tool decision event for what each value means. * `language`: Programming language of the edited file, such as `"TypeScript"`, `"Python"`, `"JavaScript"`, or `"Markdown"`. Returns `"unknown"` for unrecognized file extensions. -#### - -​ - -Active time counter +#### Active time counter Tracks actual time spent actively using Claude Code, excluding idle time. This metric is incremented during user interactions, such as typing and reading responses, and during CLI processing, such as tool execution and AI response generation. **Attributes** : * All standard attributes * `type`: `"user"` for keyboard interactions, `"cli"` for tool execution and AI responses -### - -​ - -Events +### Events Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured): -#### - -​ - -Event correlation attributes +#### Event correlation attributes When a user submits a prompt, Claude Code may make multiple API calls and run several tools. The `prompt.id` attribute lets you tie all of those events back to the single prompt that triggered them. @@ -751,11 +615,7 @@ * `request_id` on the API events, persisted as `requestId` on the transcript’s assistant entries * `tool_use_id` on `tool_result` and `tool_decision` events, and on `safety_event` events except those for the end of a turn -#### - -​ - -User prompt event +#### User prompt event Logged when a prompt is submitted, including on turns Claude Code starts on its own. **Event Name** : `claude_code.user_prompt` **Attributes** : @@ -770,11 +630,7 @@ * `command_name`: Command name when the prompt invokes one. Built-in and bundled command names such as `compact` or `debug` are emitted as-is; aliases such as `reset` emit as typed rather than the canonical name. Custom, plugin, and MCP command names collapse to `custom` or `mcp` unless `OTEL_LOG_TOOL_DETAILS=1` is set * `command_source`: Origin of the command when present: `builtin`, `custom`, or `mcp`. Plugin-provided commands report as `custom` -#### - -​ - -Assistant response event +#### Assistant response event Logged after each API request that returns text content from the model. Only the response’s text blocks are included; thinking blocks and tool-use blocks are excluded. **Event Name** : `claude_code.assistant_response` **Attributes** : @@ -789,11 +645,7 @@ * `message.uuid`: UUID of the response’s final transcript entry. An API response is persisted as one transcript entry per content block; this is the last one, which the next turn’s `parentUuid` chains from. * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name -#### - -​ - -Tool result event +#### Tool result event Logged when a tool completes execution. Not emitted if the tool call was rejected; see the Tool decision event for rejections. **Event Name** : `claude_code.tool_result` **Attributes** : @@ -822,11 +674,7 @@ * For Agent tool or legacy Task tool: includes `subagent_type` * `tool_input` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON-serialized tool arguments. Individual values over 512 characters are truncated, and the full payload is bounded to ~4 K characters. Applies to all tools including MCP tools. -#### - -​ - -API request event +#### API request event Logged for each API request to Claude. **Event Name** : `claude_code.api_request` **Attributes** : @@ -850,11 +698,7 @@ * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. -#### - -​ - -API error event +#### API error event Logged when an API request to Claude fails. **Event Name** : `claude_code.api_error` **Attributes** : @@ -874,11 +718,7 @@ * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. -#### - -​ - -API refusal event +#### API refusal event Logged when an API request returns `stop_reason: "refusal"`. Refusals arrive on a successful response stream rather than as an HTTP error, so the `api_error` event doesn’t fire for them. This event lets you track refusal frequency and group refusals by the same attributes as `api_request` and `api_error`. **Event Name** : `claude_code.api_refusal` **Attributes** : @@ -898,11 +738,7 @@ * `category`: The `stop_details.category` value from the API response. One of `"cyber"`, `"bio"`, `"frontier_llm"`, or `"reasoning_extraction"`. Only present when `OTEL_LOG_TOOL_DETAILS=1` is set and `has_category` is `true`. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. -#### - -​ - -API request body event +#### API request body event Logged for each API request attempt when `OTEL_LOG_RAW_API_BODIES` is set. One event is emitted per attempt, so retries with adjusted parameters each produce their own event. **Event Name** : `claude_code.api_request_body` **Attributes** : @@ -918,11 +754,7 @@ * `query_source`: Subsystem that issued the request (for example, `"compact"`) * `request_body_id`: UUID that identifies this attempt’s request body. The `api_response_body` event for the attempt that succeeds carries the same value, so you can pair a response with the exact request that produced it. Requires Claude Code v2.1.274 or later -#### - -​ - -API response body event +#### API response body event Logged for each successful API response when `OTEL_LOG_RAW_API_BODIES` is set. In file mode (`OTEL_LOG_RAW_API_BODIES=file:<dir>`), Claude Code also appends one JSON line to `<dir>/index.jsonl` for each successful response, with the fields `timestamp`, `session_id`, `query_source`, `model`, `request_id`, `message_id`, `message_uuid`, `request_file`, and `response_file`. Read it to find the request and response files behind a given transcript message without querying your telemetry backend. The index file requires Claude Code v2.1.274 or later. **Event Name** : `claude_code.api_response_body` **Attributes** : @@ -941,11 +773,7 @@ * `message.id`: Message ID the API assigned to the response, the `id` field of the response body. Requires Claude Code v2.1.274 or later * `message.uuid`: UUID of the response’s final transcript entry. Together with `request_body_id`, it links a transcript message to the request and response bodies behind it. Requires Claude Code v2.1.274 or later -#### - -​ - -Tool decision event +#### Tool decision event Logged when a tool permission decision is made (accept/reject). **Event Name** : `claude_code.tool_decision` **Attributes** : @@ -1010,11 +838,7 @@ `permission_mode`, `classifier_category`, and `classifier_verdict` drop in this order on Claude Code v2.1.302 or later. `parent_agent_id`, `agent_id`, and `request_id` require v2.1.310 or later. -#### - -​ - -Safety event +#### Safety event Claude Code has stopped sending `claude_code.safety_event`: @@ -1102,11 +926,7 @@ A prompt has no category when no `category` value names its check, such as the `default` mode prompt for an edit inside your working directory. -#### - -​ - -Permission mode changed event +#### Permission mode changed event Logged when the permission mode changes, for example from `Shift+Tab` cycling, exiting plan mode, or an auto mode gate check. To group tool calls by the permission mode each was checked in, use `permission_mode` on the Tool decision event. **Event Name** : `claude_code.permission_mode_changed` **Attributes** : @@ -1118,11 +938,7 @@ * `to_mode`: The new permission mode * `trigger`: What caused the change, for example `"shift_tab"`, `"exit_plan_mode"`, or `"auto_gate_denied"`. Absent for some changes, such as when the SDK sets the permission mode through [`setPermissionMode()`](</docs/en/agent-sdk/typescript#query-object>) -#### - -​ - -Auth event +#### Auth event Logged when `/login` or `/logout` completes. **Event Name** : `claude_code.auth` **Attributes** : @@ -1136,11 +952,7 @@ * `error_category`: Categorical error kind when the action failed. The raw error message is never included * `status_code`: HTTP status code as a string when the action failed with an HTTP error -#### - -​ - -MCP server connection event +#### MCP server connection event Logged when an MCP server connects, disconnects, or fails to connect. **Event Name** : `claude_code.mcp_server_connection` **Attributes** : @@ -1159,11 +971,7 @@ * `server_name` (when `OTEL_LOG_TOOL_DETAILS=1`): Configured server name * `error` (when `OTEL_LOG_TOOL_DETAILS=1`): Full error message when the connection failed -#### - -​ - -Internal error event +#### Internal error event Logged when Claude Code catches an unexpected internal error. Only the error class name and an errno-style code are recorded. The error message and stack trace are never included. This event is not emitted when running against Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, or when `DISABLE_ERROR_REPORTING` is set. **Event Name** : `claude_code.internal_error` **Attributes** : @@ -1174,11 +982,7 @@ * `error_name`: Error class name, such as `"TypeError"` or `"SyntaxError"` * `error_code`: Node.js errno code such as `"ENOENT"` when present on the error -#### - -​ - -Plugin installed event +#### Plugin installed event Logged when a plugin finishes installing, from both the `claude plugin install` CLI command and the interactive `/plugin` UI. **Event Name** : `claude_code.plugin_installed` **Attributes** : @@ -1192,11 +996,7 @@ * `plugin.version`: Plugin version when declared in the marketplace entry. For third-party marketplaces this is included only when `OTEL_LOG_TOOL_DETAILS=1` * `marketplace.name`: Marketplace the plugin was installed from. For third-party marketplaces this is included only when `OTEL_LOG_TOOL_DETAILS=1` -#### - -​ - -Plugin loaded event +#### Plugin loaded event Logged once per enabled plugin at session start. Use this event to inventory which plugins are active across your fleet, as a complement to `plugin_installed` which records the install action itself. **Event Name** : `claude_code.plugin_loaded` **Attributes** : @@ -1218,11 +1018,7 @@ * `agent_path_count`: number of agent directories the plugin declares * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. In safe mode this event reports configured inventory only; the plugin’s commands, skills, hooks, and MCP servers don’t load. Requires Claude Code v2.1.169 or later -#### - -​ - -Skill activated event +#### Skill activated event Logged when a skill is invoked, whether Claude calls it through the Skill tool or you run it as a `/` command. **Event Name** : `claude_code.skill_activated` **Attributes** : @@ -1237,11 +1033,7 @@ * `plugin.name` (when `OTEL_LOG_TOOL_DETAILS=1` or the plugin is from an official marketplace): Name of the owning plugin when the skill is provided by a plugin * `marketplace.name` (when `OTEL_LOG_TOOL_DETAILS=1` or the plugin is from an official marketplace): Marketplace the owning plugin was installed from, when the skill is provided by a plugin -#### - -​ - -At mention event +#### At mention event Logged when Claude Code resolves an `@`-mention in a prompt. Not every mention emits an event: early-exit paths such as permission denials, oversized files, PDF reference attachments, and directory listing failures return without logging. Each time Claude Code reads a prompt, it logs at most 100 events with a `mention_type` of `"agent"` and 100 with `"mcp_resource"`. Mentions past either limit still resolve but emit no event. **Event Name** : `claude_code.at_mention` **Attributes** : @@ -1252,11 +1044,7 @@ * `mention_type`: Type of mention (`"file"`, `"directory"`, `"agent"`, `"mcp_resource"`, `"peer"`). The `"peer"` value means you mentioned [one of your other Claude Code sessions](</docs/en/cross-session-messaging>). Requires Claude Code v2.1.232 or later * `success`: Whether the mention resolved successfully (`"true"` or `"false"`) -#### - -​ - -API retries exhausted event +#### API retries exhausted event Logged once when an API request fails after more than one attempt. Emitted alongside the final `api_error` event. **Event Name** : `claude_code.api_retries_exhausted` **Attributes** : @@ -1271,11 +1059,7 @@ * `total_retry_duration_ms`: Total wall-clock time across all attempts * `speed`: `"fast"` or `"normal"` -#### - -​ - -Hook registered event +#### Hook registered event Logged once per configured hook at session start. Use this event to inventory which hooks are active across your fleet, as a complement to the per-execution `hook_execution_start` and `hook_execution_complete` events. **Event Name** : `claude_code.hook_registered` **Attributes** : @@ -1291,11 +1075,7 @@ * `plugin.name` (when `hook_source` is `"pluginHook"`): name of the contributing plugin. For plugins outside the official marketplace and built-in bundle the value is `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` * `plugin_id_hash` (when `hook_source` is `"pluginHook"`): deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count distinct contributing plugins without recording their names. Claude Code computes it as described under the plugin loaded event -#### - -​ - -Hook execution start event +#### Hook execution start event Logged when one or more hooks begin executing for a hook event. **Event Name** : `claude_code.hook_execution_start` **Attributes** : @@ -1311,11 +1091,7 @@ * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. Requires Claude Code v2.1.169 or later * `hook_definitions`: JSON-serialized hook configuration. Included only when both detailed beta tracing and `OTEL_LOG_TOOL_DETAILS=1` are enabled -#### - -​ - -Hook execution complete event +#### Hook execution complete event Logged when all hooks for a hook event have finished. **Event Name** : `claude_code.hook_execution_complete` **Attributes** : @@ -1341,11 +1117,7 @@ * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. Requires Claude Code v2.1.169 or later * `hook_definitions`: JSON-serialized hook configuration. Included only when both detailed beta tracing and `OTEL_LOG_TOOL_DETAILS=1` are enabled -#### - -​ - -Hook plugin metrics event +#### Hook plugin metrics event Logged when an official-marketplace plugin hook emits per-invocation metrics. Only plugins installed from an official Anthropic marketplace can emit these. Third-party marketplace plugins and user-configured hooks don’t emit to this event. Use this event to monitor plugin behavior such as finding rates, costs, and durations from your own observability stack. **Event Name** : `claude_code.hook_plugin_metrics` **Attributes** : @@ -1357,11 +1129,7 @@ * `hook_event`: hook event type that emitted the metrics * Up to 20 plugin-emitted metric keys. Names match `^[a-z][a-z0-9_]{0,39}$`. Values are Boolean or number. -#### - -​ - -Compaction event +#### Compaction event Logged when conversation compaction completes. **Event Name** : `claude_code.compaction` **Attributes** : @@ -1377,11 +1145,7 @@ * `error`: Error message when compaction failed * `precompute_reuse`: Only set when `trigger` is `"manual"`, or when `trigger` is `"auto"` for an [idle compaction](</docs/en/settings-reference#idlecompaction>) in an interactive terminal session. Auto-compaction can prepare a summary in the background before the context window fills, and this attribute records whether the compaction reused that prepared summary. `"hit"` means it was reused; `"miss_custom_instructions"`, `"miss_hook"`, and `"miss_not_ready"` give the reason a fresh summary was computed instead -#### - -​ - -Subagent completed event +#### Subagent completed event Logged when a [subagent](</docs/en/sub-agents>) finishes and returns its result to the conversation that started it. Use it to roll up tool use and run time by subagent type; for token or cost rollups, use the token counter and cost counter filtered to `query_source` `"subagent"`, since this event’s `total_tokens` covers only the final request. The `"subagent"` category also counts requests from agent-based hooks, which emit no subagent event. **Event Name** : `claude_code.subagent_completed` **Attributes** : @@ -1401,11 +1165,7 @@ * `model_swapped`: Whether more than one model served the subagent’s requests * `plugin_id_hash`, `plugin.name`: Present for plugin-provided agents. Official-marketplace plugin names appear verbatim; other plugin names are replaced with `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` is set -#### - -​ - -Feedback survey event +#### Feedback survey event Logged when a session quality survey is shown or answered. See [Session quality surveys](</docs/en/data-usage#session-quality-surveys>) for what the surveys collect and how to control them. **Event Name** : `claude_code.feedback_survey` **Attributes** : @@ -1419,11 +1179,7 @@ * `response`: The user’s selection on `responded` events * `enabled_via_override`: `true` when [`CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL`](</docs/en/env-vars>) is set. Emitted as a Boolean, not a string. Present on `session` survey events. Filter on this attribute to confirm the override is applied across a fleet -#### - -​ - -Retention sweep event +#### Retention sweep event Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. Read `result` to see whether the sweep ran: @@ -1452,11 +1208,7 @@ * `files_past_cutoff`: Files older than the retention period that the sweep failed to delete, for example because of a permission error or a file held open. The count also includes each stale folder the sweep finds under `skills/synced/` or `plugins/synced/`, whether or not it moves the folder to the trash. Apart from those folders, a value above zero means files outlived the configured retention period; zero isn’t proof that none did, because a failed removal of a whole directory counts toward `error_count` instead * `error_count`: Number of errors the sweep encountered while listing or deleting files -#### - -​ - -Managed settings resolved event +#### Managed settings resolved event Logged with the [managed settings](</docs/en/managed-settings>) a session resolved: once at session start, again when either the managed settings or the [policy helper](</docs/en/managed-settings#compute-the-policy-with-a-helper-program>)’s state changes during the session, and when Claude Code refuses to start or ends the session for one of the reasons the `error.type` attribute lists. Use this event to find machines running on an unexpected managed source, machines whose policy helper is failing, and the reason a machine refused to start. Requires Claude Code v2.1.274 or later. By default, the event carries the managed sources and the policy helper’s state but not the settings themselves. To add the redacted `managed_settings.settings` attribute and the `managed_settings.resolved_sha256` digest, set `OTEL_LOG_MANAGED_SETTINGS=1`: @@ -1500,19 +1252,11 @@ For example, managed settings with `apiKeyHelper`, two `env` variables, and a deny rule are exported as `{"apiKeyHelper":"[REDACTED]","env":{"HTTPS_PROXY":"[REDACTED]","CLAUDE_CODE_ENABLE_TELEMETRY":"[REDACTED]"},"permissions":{"deny":["Read([REDACTED])"]}}`. Claude Code cuts the value at 8 KB of UTF-8, and the cut value isn’t valid JSON * `managed_settings.settings_truncated` (when `managed_settings.settings` is present): `true` when Claude Code cut `managed_settings.settings` at 8 KB, `false` otherwise. Emitted as a Boolean, not a string -## - -​ - -Interpret metrics and events data +## Interpret metrics and events data The exported metrics and events support a range of analyses: -### - -​ - -Usage monitoring +### Usage monitoring Metric| Analysis Opportunity ---|--- @@ -1522,11 +1266,7 @@ To compare active users across surfaces, set `OTEL_METRICS_INCLUDE_ENTRYPOINT=true` to add `app.entrypoint` to metrics and events. Then count distinct `user.account_uuid` values per entrypoint on `claude_code.user_prompt` events, or on `claude_code.token.usage` if you export only metrics. For example, use `cli` for interactive CLI sessions, and group `claude-desktop`, `claude-desktop-3p`, and `remote_desktop` for the Claude Desktop Code tab. `user.account_uuid` doesn’t identify people in Claude Tag channel sessions and is missing from sessions with no Claude account: see Attribute actions to users. When one person starts many sessions, or a session receives no prompt, `claude_code.session.count` goes up without adding an active user. -### - -​ - -Cost monitoring +### Cost monitoring The `claude_code.cost.usage` metric helps with: @@ -1538,11 +1278,7 @@ Claude Code counts each streaming response toward the cost and token metrics exactly once, including when a gateway or proxy behind `ANTHROPIC_BASE_URL` streams usage progressively across multiple frames. -### - -​ - -Alerting and segmentation +### Alerting and segmentation Common alerts to consider: @@ -1552,19 +1288,11 @@ All metrics can be segmented by the standard attributes. The `model` attribute is available on `claude_code.token.usage`, `claude_code.cost.usage`, and `claude_code.lines_of_code.count`. Per-model breakdowns of commits can only be approximated by joining against the token or cost metrics on `session.id`, since one session can span multiple models. Filter the token or cost side to rows where `query_source` is `"main"` so auxiliary and subagent requests don’t attribute the session’s commits to a model that didn’t make them. -### - -​ - -Detect retry exhaustion +### Detect retry exhaustion Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records the number of attempts. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15; with [`CLAUDE_CODE_RETRY_WATCHDOG`](</docs/en/env-vars>) set, the default is higher and there is no cap. When the request exhausts all retries on a transient error, `attempt` is at most one more than that effective limit: 11 by default. A lower value can still mean the retries ran out: `attempt` starts again from `1` each time Claude Code re-issues the request after a streaming failure. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. -### - -​ - -Event analysis +### Event analysis The event data describes each Claude Code interaction in detail: **Tool usage patterns** : analyze tool result events to identify: @@ -1575,11 +1303,7 @@ **Performance monitoring** : track API request durations and tool execution times to identify performance bottlenecks. -### - -​ - -Map input tokens to OpenTelemetry GenAI semantic conventions +### Map input tokens to OpenTelemetry GenAI semantic conventions Claude Code exports input token counts as they appear in the API response’s usage block, so these values exclude tokens read from or written to the [prompt cache](</docs/en/prompt-caching>): @@ -1596,29 +1320,17 @@ * `cache_read_tokens` maps to `gen_ai.usage.cache_read.input_tokens` * `cache_creation_tokens` maps to `gen_ai.usage.cache_write.input_tokens`. Older versions of the conventions name the cache write attribute `gen_ai.usage.cache_creation.input_tokens`, so use the name your backend expects. -## - -​ - -Audit security events +## Audit security events OpenTelemetry events are the audit data source for Claude Code activity. Every event carries identity attributes that tie tool calls, MCP activity, and permission decisions back to the user who triggered them. The OTLP logs exporter can deliver these events to any Security Information and Event Management (SIEM) platform with an OTLP receiver, or to an OpenTelemetry Collector that forwards to your SIEM. -### - -​ - -Attribute actions to users +### Attribute actions to users The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account or, in a [cloud session](</docs/en/claude-code-on-the-web>), when the session’s own credentials carry them, plus `user.id` and the per-session `session.id`. `user.id` is an installation-scoped identifier, except in sessions signed in to a [Claude apps gateway](</docs/en/claude-apps-gateway>) through `/login`, where it is the IdP subject from the gateway-issued token. In a session a developer starts, MCP tool calls, Bash commands, and file edits are therefore attributed to that developer. Claude Code doesn’t act under a separate service account there; the identity recorded on each event is the developer’s own Claude account, or the developer’s IdP identity on a [Claude apps gateway](</docs/en/claude-apps-gateway>) session. In Claude Tag channel sessions, Claude works as your organization’s [shared identity](</docs/en/cloud-environments#set-the-environment-a-claude-tag-channel-uses>) instead. When Claude Code authenticates with a direct API key, or against Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper. Claude apps gateway sessions need none of this: see Standard attributes for the identity their exports carry. export OTEL_RESOURCE_ATTRIBUTES="enduser.id=jdoe@example.com,enduser.directory_id=S-1-5-21-..." -### - -​ - -Audit MCP activity +### Audit MCP activity To capture MCP server activity with full call detail, enable the logs exporter and set `OTEL_LOG_TOOL_DETAILS=1`. Each MCP operation then produces structured events that carry the server name, tool name, and call arguments alongside the standard identity attributes: @@ -1634,11 +1346,7 @@ * `tool_decision`: keeps `tool_source` and a `tool_name` redacted to the literal `"mcp_tool"` for user-configured servers, omits argument content. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, it also keeps the `mcp_server_name`/`mcp_tool_name` pair inside `tool_parameters` * `mcp_server_connection`: omits `server_name` and the error message, but keeps `is_plugin`, `plugin_id_hash`, and `plugin.name`, with non-Anthropic plugin names redacted to the literal `"third-party"`, so plugin-provided servers remain distinguishable without detailed logging -### - -​ - -Map security questions to events +### Map security questions to events Rows for `safety_event` apply only to a session on v2.1.307 through v2.1.311 that still sends the event. When building detection rules, look up the signal you want to monitor and query your backend for the corresponding event and attributes: @@ -1661,11 +1369,7 @@ Claude Code emits the raw event stream only. Anomaly detection, baselining, correlation across sessions, and alerting are the responsibility of your SIEM or observability backend. -### - -​ - -Map egress paths to managed controls and events +### Map egress paths to managed controls and events The table pairs paths that can carry session content off a machine, plus local retention, with the [managed settings](</docs/en/managed-settings>) keys that restrict them and the events that record them. For what Claude Code itself sends to Anthropic, such as `/feedback` reports, see [Data usage](</docs/en/data-usage>). The names link to their reference entries, which give the values and defaults. @@ -1688,11 +1392,7 @@ `OTEL_LOG_TOOL_DETAILS=1` adds command strings, server and tool names, and tool input to these events. That detail can contain the same sensitive content as the session itself, so enable it only when your collector is approved to hold that content. -### - -​ - -Check the retention sweep +### Check the retention sweep To give every machine the same retention period, set [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) in [managed settings](</docs/en/managed-settings>). To check that machines run the sweep with that value, collect the `retention_sweep` event. `period_days` and the counters are strings, so cast them to numbers before you compare them. @@ -1712,11 +1412,7 @@ The sweep doesn’t cover every path. [Kept until you delete them](</docs/en/claude-directory#kept-until-you-delete-them>) lists what stays, and [Clear local data](</docs/en/claude-directory#clear-local-data>) shows how to remove it. -### - -​ - -Send events to a SIEM +### Send events to a SIEM Point `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` at your SIEM’s OTLP receiver, or at an OpenTelemetry Collector that forwards to your SIEM’s native ingest API. The following managed-settings example exports events only, with full tool detail enabled for MCP and Bash auditing: @@ -1733,39 +1429,23 @@ To confirm events arrive, submit a prompt in a session running under this configuration and check your SIEM for the `claude_code.user_prompt` event. If nothing arrives, start Claude Code with `claude --debug-file <path>` and check that log for `[3P telemetry]` export errors. -## - -​ - -Backend considerations +## Backend considerations Your choice of metrics, logs, and traces backends determines the types of analyses you can perform: -### - -​ - -Backends for metrics +### Backends for metrics * **Time series databases** : Rate calculations, aggregated metrics * **Columnar stores** : Complex queries, unique user analysis * **Full-featured observability platforms** : Advanced querying, visualization, alerting -### - -​ - -Backends for events and logs +### Backends for events and logs * **Log aggregation systems** : Full-text search, log analysis * **Columnar stores** : Structured event analysis * **Full-featured observability platforms** : Correlation between metrics and events -### - -​ - -Backends for traces +### Backends for traces Choose a backend that supports distributed trace storage and span correlation: @@ -1774,11 +1454,7 @@ For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries. -## - -​ - -Service information +## Service information All metrics and events are exported with the following resource attributes: @@ -1792,19 +1468,11 @@ If your collector pipelines or dashboards filter on `service.name = claude-code`, add `claude-code-desktop` to the filter to also capture telemetry from local Code tab sessions. -## - -​ - -ROI measurement resources +## ROI measurement resources For a comprehensive guide on measuring return on investment for Claude Code, including telemetry setup, cost analysis, productivity metrics, and automated reporting, see the [Claude Code ROI Measurement Guide](<https://github.com/anthropics/claude-code-monitoring-guide>). This repository provides ready-to-use Docker Compose configurations, Prometheus and OpenTelemetry setups, and templates for generating productivity reports integrated with tools like Linear. -## - -​ - -Security and privacy +## Security and privacy * OpenTelemetry export to your backend is opt-in and requires explicit configuration. For Anthropic’s separate operational telemetry and how to disable it, see [Data usage](</docs/en/data-usage#telemetry-services>) * By default, raw file contents and code snippets aren’t included in metrics or events. If you set a variable such as `OTEL_LOG_TOOL_DETAILS` or `OTEL_LOG_RAW_API_BODIES`, events can include them. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below @@ -1834,10 +1502,6 @@ * With `=1`, Claude Code emits `api_request_body` and `api_response_body` log events for each API call. The events’ `body` attribute carries the JSON-serialized payload, truncated at the content limit (60 KB by default) * With `=file:<dir>`, Claude Code writes untruncated bodies to `.request.json` and `.response.json` files under that directory, and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. For each successful response, Claude Code also appends one line to `index.jsonl` in that directory, linking the response file to the request file that produced it and to the transcript message it became. Each line holds no message content, and the API response body event section lists its fields. The index file requires Claude Code v2.1.274 or later -## - -​ - -Monitor Claude Code on Amazon Bedrock +## Monitor Claude Code on Amazon Bedrock For detailed Claude Code usage monitoring guidance for Amazon Bedrock, see [Claude Code Monitoring Implementation (Amazon Bedrock)](<https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md>).
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -677,7 +677,8 @@ * `plugin.name`: Owning plugin when the active skill or subagent is provided by a plugin. Official-marketplace plugin names appear verbatim. Third-party plugin names are replaced with `"third-party"`. Absent when neither the skill nor the subagent has an owning plugin. * `marketplace.name`: Marketplace the owning plugin was installed from. Only emitted for official-marketplace plugins, even with `OTEL_LOG_TOOL_DETAILS=1` set. Absent otherwise. * `mcp_server.name`: MCP server whose tool result this request consumed. Built-in, claude.ai-proxied, and official-registry server names appear verbatim. User-configured server names are replaced with `"custom"`. Absent when the request consumed no MCP tool result. Before v2.1.222, Claude Code set this attribute on every request after an MCP tool call, not only on requests that consumed a tool result, so dashboards that aggregate it show a step down after you upgrade. - * `mcp_tool.name`: MCP tool whose result this request consumed, with the same redaction and version behavior as `mcp_server.name`. Absent when the request consumed no MCP tool result. + * From v2.1.312, the name of a remote server with a fixed URL that a plugin from Anthropic’s official marketplace declares also appears verbatim, as `plugin_<plugin>_<server>`. That name is replaced with `"custom"` when the plugin’s marketplace copy didn’t come from Anthropic’s registered source, such as one mounted from a seed directory in a cloud session. + * `mcp_tool.name`: MCP tool whose result this request consumed, with the same redaction and version behavior as `mcp_server.name`, except that it can read `"custom"` when `mcp_server.name` shows a `plugin_<plugin>_<server>` name. Absent when the request consumed no MCP tool result. #### @@ -970,7 +971,7 @@ * The auto mode classifier, whose verdict the same event records in `classifier_verdict` * A grant for the rest of the session, given at an earlier permission prompt in the same interactive CLI session * The tool being inherently safe -The `source` value doesn’t indicate which of these sources matched. To find which one refused a call, look for the Safety event with the same `tool_use_id` and read its `category` and `rule_source` attributes. Some refused calls have no safety event. Claude Code also reports `"config"` when the permission prompt request itself fails. For example, that request fails when the Agent SDK’s [`canUseTool`](</docs/en/agent-sdk/typescript#canusetool>) callback or the [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) tool returns an invalid result, or when the input stream closes while the request is pending. +The `source` value doesn’t indicate which of these sources matched. When `classifier_verdict` is present, it gives the classifier outcome that decided the call. No `tool_decision` attribute names the permission rule or setting that refused the call. Claude Code also reports `"config"` when the permission prompt request itself fails. For example, that request fails when the Agent SDK’s [`canUseTool`](</docs/en/agent-sdk/typescript#canusetool>) callback or the [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) tool returns an invalid result, or when the input stream closes while the request is pending. * `"hook"`: A `PreToolUse` or `PermissionRequest` hook returned the decision. * `"user_permanent"`: Emitted when the user chose “Yes, and don’t ask again for …” at a permission prompt, which saves an allow rule to their personal settings. In the interactive CLI this is emitted only for that choice itself; later calls that match the saved rule emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the initial choice and later rule matches emit `"user_permanent"`. Treated as an accept. * `"user_temporary"`: Emitted when the user chose “Yes” at a permission prompt for a one-time approval, or chose an option that grants access for the rest of the session on a file edit or read prompt. In the interactive CLI this is emitted only for the choice itself; later calls allowed by that session-scoped grant emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the choice and later matches emit `"user_temporary"`. Treated as an accept. @@ -1015,7 +1016,18 @@ Safety event -Logged when a check refuses a tool call or requires a permission prompt, except for calls without a safety event. Also logged when the [sandbox’s network proxy](</docs/en/sandboxing#network-isolation>) refuses a connection or request, and when a hook blocks a result. Requires Claude Code v2.1.307 or later. The event exports with the other events and has no separate setting. The event’s own attributes hold no command text, file paths, host names, or MCP server and tool names. The record also carries the standard attributes every event has, which can include `workspace.host_paths` and the repository attributes. To see the command or MCP tool behind an event, set `OTEL_LOG_TOOL_DETAILS=1` and read `tool_parameters` on the matching `tool_decision` event. **Event Name** : `claude_code.safety_event` **Attributes** : +Claude Code has stopped sending `claude_code.safety_event`: + + * **v2.1.312 and later** : these versions don’t send the event, and no setting turns it on + * **v2.1.307 through v2.1.311** : a session stops sending the event at its next feature-flag refresh. A session that doesn’t [fetch feature flags](</docs/en/env-vars#features-that-need-feature-flag-fetching>), such as on Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, can keep sending it. + +To see refused tool calls, query `tool_decision` events, which show that a call was refused but not always which check refused it. The event details here describe events from v2.1.307 through v2.1.311, where a safety event records cases such as these: + + * A check refuses a tool call or requires a permission prompt, except for calls without a safety event + * The [sandbox’s network proxy](</docs/en/sandboxing#network-isolation>) refuses a connection or request + * A hook blocks a result or the end of a turn + +The event exports with the other events and has no separate setting. The event’s own attributes hold no command text, file paths, host names, or MCP server and tool names. The record also carries the standard attributes every event has, which can include `workspace.host_paths` and the repository attributes. To see the command or MCP tool behind an event, set `OTEL_LOG_TOOL_DETAILS=1` and read `tool_parameters` on the matching `tool_decision` event. **Event Name** : `claude_code.safety_event` **Attributes** : * All standard attributes * `event.name`: `"safety_event"` @@ -1413,15 +1425,20 @@ Retention sweep event -Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. When Claude Code can’t safely determine the retention period, it pauses the sweep and emits the event with `result` set to `"skipped"` and a `skip_reason`. When [managed settings](</docs/en/server-managed-settings>) set `cleanupPeriodDays`, the managed value pins the retention period and the sweep runs even when a settings file in a lower-priority scope is broken or invalid. When `managed-settings.json` itself can’t be read, Claude Code still pauses the sweep unless the [managed tier](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) supplies `cleanupPeriodDays` from elsewhere, such as server-managed settings or a `managed-settings.d/` drop-in beside the broken file. The deletion counter attributes are present only when `result` is `"complete"`. **Event Name** : `claude_code.retention_sweep` **Attributes** : +Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. Read `result` to see whether the sweep ran: + + * `"complete"`: the sweep ran, and the event carries its counts + * `"skipped"`: Claude Code couldn’t safely determine the retention period, so it paused the sweep and the event carries no counts. If `skip_reason` is `"settings_unknowable"` or `"settings_invalid_key_set"`, fix the settings error that `/status` reports on that machine so a later session can run the sweep + +When [managed settings](</docs/en/server-managed-settings>) set `cleanupPeriodDays`, the managed value pins the retention period and the sweep runs even when a settings file in a lower-priority scope is broken or invalid. **Event Name** : `claude_code.retention_sweep` **Attributes** : * All standard attributes * `event.name`: `"retention_sweep"` * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `result`: `"complete"` when the sweep ran, `"skipped"` when Claude Code paused it - * `period_days`: The `cleanupPeriodDays` value from merged settings, in days, or `30` when no source sets it. On skipped events, the value the sweep would have used, computed from the settings sources Claude Code could read - * `used_default`: `"true"` when no readable settings source sets `cleanupPeriodDays`, `"false"` otherwise. On complete events, `"true"` means the 30-day default applied + * `period_days`: The retention period the sweep started with, in days: `cleanupPeriodDays` from merged settings, with any change from a [`settings.read` hook](</docs/en/plugins/mods/events#settings-read-hook>) applied. `30` when that leaves the key unset. On skipped events, the value the sweep would have used, computed from the settings sources Claude Code could read + * `used_default`: `"true"` when `period_days` fell back to `30`, `"false"` otherwise. On complete events, `"true"` means the 30-day default applied * `skip_reason`: Why Claude Code paused the sweep. Present only when `result` is `"skipped"`: * `"user_source_disabled"`: User settings are excluded, for example by the [`--setting-sources`](</docs/en/cli-reference#cli-flags>) flag or the SDK’s [`settingSources`](</docs/en/agent-sdk/typescript#options>) option, and no enabled source provides `cleanupPeriodDays` * `"settings_unknowable"`: A settings file couldn’t be read or parsed, so `cleanupPeriodDays` or `desktopSessionCleanupPeriodDays` may be set to a value Claude Code can’t see @@ -1623,7 +1640,7 @@ Map security questions to events -When building detection rules, look up the signal you want to monitor and query your backend for the corresponding event and attributes: +Rows for `safety_event` apply only to a session on v2.1.307 through v2.1.311 that still sends the event. When building detection rules, look up the signal you want to monitor and query your backend for the corresponding event and attributes: Signal| Event| Key attributes ---|---|--- @@ -1632,8 +1649,9 @@ Auto mode classifier allowed or blocked a tool call, or Claude Code denied the call without a classifier verdict| `tool_decision` where `classifier_verdict` is present. For a denial without a verdict, `classifier_verdict` is `"no_verdict"` or `"unavailable"`| `classifier_verdict`, `permission_mode`, `tool_name`; `classifier_category` when you set `OTEL_LOG_TOOL_DETAILS=1` Permission mode escalation| `permission_mode_changed`| `from_mode`, `to_mode`, `trigger` Which permission mode each tool call was checked in, including calls subagents make| `tool_decision`| `permission_mode`, `session.id` -Policy hook blocked an action| `hook_execution_complete`| `hook_event`, `num_blocking` -Which tool call a hook refused, and which result or turn end a hook blocked| `safety_event` where `category` is `"hook"` and `decision` is `"reject"` for a refused call, or `category` is `"hook_review"` for a blocked result or turn end| `category`, `decision`, `hook_event`; `tool_use_id` for a tool call +Policy hook blocked an action| `hook_execution_complete`, which isn’t tied to a call or to `tool_use_id`| `hook_event`, `num_blocking` +Tool call a hook refused| `tool_decision` where `decision` is `"reject"` and `source` is `"hook"`| `decision`, `source`, `tool_use_id` +Which result or turn end a hook blocked| `safety_event` where `category` is `"hook_review"`| `category`, `hook_event`; `tool_use_id` for a tool call Sandbox’s network proxy refused a connection or request from a Bash or PowerShell command| `safety_event` where `sandbox_violation_count` is present and isn’t `"0"`| `sandbox_violation_count`, `category`, `sandbox_enabled`, `tool_use_id` Login, logout, and authentication failure| `auth`| `action`, `success`, `error_category` MCP server connect or failure| `mcp_server_connection`| `status`, `server_name`, `is_plugin`, `error_code`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -138,15 +138,15 @@ Metrics cardinality control -The following environment variables control which attributes are included in metrics to manage cardinality: +The following environment variables control which attributes are included in metrics and events to manage cardinality: Environment Variable| Description| Default Value| Example to Disable ---|---|---|--- -`OTEL_METRICS_INCLUDE_SESSION_ID`| Include session.id and, on cloud sessions, ccr.session.id attributes in metrics| `true`| `false` -`OTEL_METRICS_INCLUDE_VERSION`| Include app.version attribute in metrics| `false`| `true` -`OTEL_METRICS_INCLUDE_ACCOUNT_UUID`| Include user.account_uuid and user.account_id attributes in metrics| `true`| `false` -`OTEL_METRICS_INCLUDE_ENTRYPOINT`| Include app.entrypoint attribute in metrics| `false`| `true` -`OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES`| Include keys from `OTEL_RESOURCE_ATTRIBUTES` as attributes on metric datapoints| `true`| `false` +`OTEL_METRICS_INCLUDE_SESSION_ID`| Include session.id and cloud sessions’ ccr.session.id attributes in metrics and events| `true`| `false` +`OTEL_METRICS_INCLUDE_VERSION`| Include app.version attribute in metrics and events| `false`| `true` +`OTEL_METRICS_INCLUDE_ACCOUNT_UUID`| Include user.account_uuid and user.account_id attributes in metrics and events| `true`| `false` +`OTEL_METRICS_INCLUDE_ENTRYPOINT`| Include app.entrypoint attribute in metrics and events| `false`| `true` +`OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES`| Include keys from `OTEL_RESOURCE_ATTRIBUTES` as attributes on metric datapoints and events| `true`| `false` `OTEL_METRICS_INCLUDE_REPOSITORY`| Include `vcs.*` repository identity attributes on metrics and events. Requires Claude Code v2.1.269 or later| `false`| `true` Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. @@ -480,7 +480,7 @@ export OTEL_METRICS_EXPORTER=otlp export OTEL_LOGS_EXPORTER=otlp export OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=http/protobuf - export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://metrics.example.com:4318 + export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://metrics.example.com:4318/v1/metrics export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://logs.example.com:4317 @@ -523,7 +523,7 @@ By default, metrics and events from a cloud session carry the standard attributes, including `session.id`, `ccr.session.id`, and `organization.id`, so you can filter by session or organization without extra configuration. The `ccr.session.id` value is the session’s `CLAUDE_CODE_REMOTE_SESSION_ID`. To turn it into the session’s transcript URL, see [Link output back to the session](</docs/en/cloud-environments#link-output-back-to-the-session>). To tell cloud sessions apart, group or filter on `ccr.session.id`, not `session.id`. To attribute telemetry in more detail, use these options: - * **Identify Claude Tag sessions** : set `OTEL_METRICS_INCLUDE_ENTRYPOINT=true`, as described under Metrics cardinality control. Metrics then carry `app.entrypoint`, whose value is `claude-in-slack` for Claude Tag sessions. + * **Identify Claude Tag sessions** : set `OTEL_METRICS_INCLUDE_ENTRYPOINT=true`, as described under Metrics cardinality control. Metrics and events then carry `app.entrypoint`, whose value is `claude-in-slack` for Claude Tag sessions. * **Add custom attributes** : set `OTEL_RESOURCE_ATTRIBUTES` in the same place you set the other `OTEL_*` variables for those sessions. If you `export` it in the environment’s [setup script](</docs/en/cloud-environments#setup-scripts>) instead, the value doesn’t reach Claude Code: the setup script is a separate Bash script that runs before Claude Code launches, and variables it exports end with it. In Claude Tag channel sessions, Claude works as your organization’s [shared identity](</docs/en/cloud-environments#set-the-environment-a-claude-tag-channel-uses>) rather than as any member, so don’t rely on the `user.*` attributes to identify who tagged Claude. @@ -547,7 +547,7 @@ `session.id`| Claude Code’s own session ID, which `/clear` replaces| `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) `ccr.session.id`| Cloud session identifier, the value of `CLAUDE_CODE_REMOTE_SESSION_ID`, on sessions that run in a [cloud environment](</docs/en/cloud-environments>)| `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) `app.version`| Current Claude Code version| `OTEL_METRICS_INCLUDE_VERSION` (default: false) -`app.entrypoint`| How the session was launched, such as `cli`, `sdk-cli`, `sdk-ts`, `sdk-py`, `claude-vscode`, or `claude-in-slack` for Claude Tag sessions| `OTEL_METRICS_INCLUDE_ENTRYPOINT` (default: false) +`app.entrypoint`| How the session was launched, such as `cli`, `sdk-cli`, `sdk-ts`, `sdk-py`, `claude-vscode`, `claude-desktop` for Claude Desktop Code tab sessions outside the cloud, `claude-desktop-3p` for the same sessions on a [third-party deployment](<https://claude.com/docs/third-party/claude-desktop/overview>), or `claude-in-slack` for Claude Tag sessions. Cloud session values include `remote`, plus `remote_desktop` and `remote_mobile` for sessions you start from Claude Desktop or the mobile app| `OTEL_METRICS_INCLUDE_ENTRYPOINT` (default: false) `organization.id`| Organization UUID (when authenticated)| Always included when available `user.account_uuid`| Account UUID (when authenticated)| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) `user.account_id`| Account ID in tagged format matching Anthropic admin APIs (when authenticated), such as `user_01BWBeN28...`| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) @@ -597,7 +597,7 @@ Metric Name| Description| Unit ---|---|--- -`claude_code.session.count`| Count of CLI sessions started| none +`claude_code.session.count`| Count of sessions started| none `claude_code.lines_of_code.count`| Count of lines of code modified| none `claude_code.pull_request.count`| Number of pull requests created| none `claude_code.commit.count`| Number of git commits created| none @@ -622,7 +622,7 @@ Session counter -Incremented at the start of each session. **Attributes** : +Incremented at the start of each session. To count people instead, see Usage monitoring. **Attributes** : * All standard attributes * `start_type`: How the session was started. One of `"fresh"`, `"resume"`, `"continue"`, or `"agents_view"`. The `"agents_view"` value identifies the `claude agents` dashboard process, a user-launched local UI rather than a conversational session. Filter on this value to separate UI process launches from conversational sessions in your dashboards. @@ -1500,9 +1500,10 @@ Metric| Analysis Opportunity ---|--- `claude_code.token.usage`| Break down by token `type`, user, team, model, `skill.name`, `plugin.name`, or `agent.name` -`claude_code.session.count`| Track adoption and engagement over time `claude_code.lines_of_code.count`| Measure productivity by tracking code additions and removals, broken down by model `claude_code.commit.count` & `claude_code.pull_request.count`| Understand impact on development workflows + +To compare active users across surfaces, set `OTEL_METRICS_INCLUDE_ENTRYPOINT=true` to add `app.entrypoint` to metrics and events. Then count distinct `user.account_uuid` values per entrypoint on `claude_code.user_prompt` events, or on `claude_code.token.usage` if you export only metrics. For example, use `cli` for interactive CLI sessions, and group `claude-desktop`, `claude-desktop-3p`, and `remote_desktop` for the Claude Desktop Code tab. `user.account_uuid` doesn’t identify people in Claude Tag channel sessions and is missing from sessions with no Claude account: see Attribute actions to users. When one person starts many sessions, or a session receives no prompt, `claude_code.session.count` goes up without adding an active user. ### @@ -1788,7 +1789,7 @@ Security and privacy * OpenTelemetry export to your backend is opt-in and requires explicit configuration. For Anthropic’s separate operational telemetry and how to disable it, see [Data usage](</docs/en/data-usage#telemetry-services>) - * Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below + * By default, raw file contents and code snippets aren’t included in metrics or events. If you set a variable such as `OTEL_LOG_TOOL_DETAILS` or `OTEL_LOG_RAW_API_BODIES`, events can include them. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below * When authenticated via OAuth, `user.email` is included in telemetry attributes, sent only to the OTel endpoint you configure, never to Anthropic. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1`. When enabled: * `user_prompt` events carry the prompt text in two attributes, `prompt` and `prompt_text`. If you drop or mask the event’s prompt text by attribute name in your collector, name both attributes in the rule This OpenTelemetry Collector `attributes` processor deletes both attributes in the pipelines that list it:
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -297,6 +297,8 @@ `error_class`| The error category in identifier form, with characters outside letters, digits, and underscores replaced by `_`, such as `Error_ENOENT` or `ShellError`. Carries the category even when `error` carries the full message. Requires Claude Code v2.1.268 or later| **`claude_code.hook`** This span appears only when detailed beta tracing is active, which requires `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>). Set the pair in your shell, user settings, or managed settings; both variables are ignored in [project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` alone doesn’t produce it. In interactive CLI sessions, detailed beta tracing also requires your organization to be allowlisted for the feature. Agent SDK and non-interactive `-p` sessions don’t require allowlisting. + +Set `ENABLE_BETA_TRACING_DETAILED` only for debugging, not in production. Detailed beta tracing has a high export volume, and its content attributes aren’t part of the stable span schema. Attribute| Description| Gated by ---|---|---
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1514,7 +1514,7 @@ * Identifying high-usage sessions for optimization * Attributing spend to specific skills, plugins, or subagent types via the `skill.name`, `plugin.name`, and `agent.name` attributes -Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, Amazon Bedrock, or Google Cloud’s Agent Platform). +Cost metrics are approximations. For official billing data, see [Manage costs for your organization](</docs/en/costs#manage-costs-for-your-organization>). Claude Code counts each streaming response toward the cost and token metrics exactly once, including when a gateway or proxy behind `ANTHROPIC_BASE_URL` streams usage progressively across multiple frames.
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -510,7 +510,7 @@ Anyone who uses an environment can read its variables, so don’t put a credential there, such as a collector token in `OTEL_EXPORTER_OTLP_HEADERS`. A [network secret](</docs/en/cloud-environments#add-network-secrets>) on the environment doesn’t help either, because Claude Code’s own telemetry export is one of the [requests that never get the secret](</docs/en/cloud-environments#requests-that-never-get-the-credential>). If your collector requires a credential, configure the whole export through server-managed settings instead, because when you set a credential there, Claude Code removes endpoint variables set outside managed settings. Keep these constraints in mind when you configure telemetry for cloud sessions: * **Let sessions reach the collector** : Claude Code sends the export through the session’s network, so whether it reaches the host in your `OTEL_EXPORTER_OTLP_ENDPOINT` depends on the environment’s [network access level](</docs/en/cloud-environments#access-levels>). If sessions can’t reach the collector’s domain at the level you chose, [add the domain to the environment’s allowlist](</docs/en/cloud-environments#allow-specific-domains>), because no server-managed setting adds domains to an environment’s network allowlist. - * **Claude Tag channels use organization-level environments** : channel sessions run in organization-level environments rather than members’ personal ones, so make the allowlist and any environment-variable changes on the [shared environment](</docs/en/cloud-environments#organization-shared-environments>) set as your organization’s default or pinned to the channel. + * **Claude Tag channels** : make the allowlist and any environment-variable changes on the [shared environment](</docs/en/cloud-environments#organization-shared-environments>) set as your organization’s default or pinned to the channel. * **Cowork is configured separately** : Cowork sessions don’t receive server-managed settings, as the [surface coverage table](</docs/en/model-config#surface-coverage>) shows, so the server-managed `env` block doesn’t configure their telemetry. ### @@ -1424,6 +1424,7 @@ * `"user_source_disabled"`: User settings are excluded, for example by the [`--setting-sources`](</docs/en/cli-reference#cli-flags>) flag or the SDK’s [`settingSources`](</docs/en/agent-sdk/typescript#options>) option, and no enabled source provides `cleanupPeriodDays` * `"settings_unknowable"`: A settings file couldn’t be read or parsed, so `cleanupPeriodDays` or `desktopSessionCleanupPeriodDays` may be set to a value Claude Code can’t see * `"settings_invalid_key_set"`: Settings have validation errors and `cleanupPeriodDays` or `desktopSessionCleanupPeriodDays` is explicitly set, so falling back to the default could delete or keep files against that setting + * `"remote_settings_unknowable"`: A session in Claude Desktop’s Code tab on a third-party deployment requested [server-managed settings](</docs/en/server-managed-settings>). It received no usable response, so `cleanupPeriodDays` may be set to a value Claude Code can’t see * `transcripts_deleted`: Number of session transcripts, the top-level `~/.claude/projects/*/*.jsonl` files, that the sweep deleted * `transcripts_exempted_desktop`: Number of transcripts past the retention period that the sweep kept under the [Claude Desktop and Cowork rule](</docs/en/claude-directory#cleaned-up-automatically>). These don’t count toward `files_past_cutoff`. Requires Claude Code v2.1.248 or later * `session_files_deleted`: Number of artifacts the session-files sweep deleted: transcripts plus per-session companion files such as sidecars, recordings, and tool results
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -839,6 +839,7 @@ * `output_tokens`: Number of output tokens * `cache_read_tokens`: Number of tokens read from cache * `cache_creation_tokens`: Number of tokens used for cache creation + * `cache_creation_5m_tokens`, `cache_creation_1h_tokens`: the number of tokens the API response reports as written to the cache with a five-minute [cache lifetime](</docs/en/prompt-caching#cache-lifetime>) and the number written with a one-hour lifetime. Both are `0` when the API response doesn’t report them, even when `cache_creation_tokens` is above zero. Requires Claude Code v2.1.300 or later * `request_id`: API request ID, such as `"req_011..."`, described under Event correlation attributes. * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header; see the event correlation attributes table for when it’s present * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -604,7 +604,7 @@ `claude_code.code_edit_tool.decision`| Count of code editing tool permission decisions| none `claude_code.active_time.total`| Total active time| s -When `prometheus` is the only exporter listed in `OTEL_METRICS_EXPORTER`, Claude Code omits the `USD`, `tokens`, and `s` units from the exported metrics so the scrape stays valid Prometheus text format. Metric names don’t change, and configurations that combine exporters, such as `otlp,prometheus`, keep the units. Before v2.1.216, the Prometheus scrape included OpenMetrics-only `# UNIT` lines that some scrapers rejected. +When `prometheus` is the only exporter listed in `OTEL_METRICS_EXPORTER`, Claude Code omits the `USD`, `tokens`, and `s` units from the exported metrics so the scrape stays valid Prometheus text format. Metric names don’t change, and configurations that combine exporters, such as `otlp,prometheus`, keep the units. ### @@ -967,11 +967,11 @@ * The auto mode classifier, whose verdict the same event records in `classifier_verdict` * A grant for the rest of the session, given at an earlier permission prompt in the same interactive CLI session * The tool being inherently safe -The `source` value doesn’t indicate which of these sources matched. To find which one refused a call, look for the Safety event with the same `tool_use_id` and read its `category` and `rule_source` attributes. Some refused calls have no safety event. Claude Code also reports `"config"` when the permission prompt request itself fails. For example, that request fails when the Agent SDK’s [`canUseTool`](</docs/en/agent-sdk/typescript#canusetool>) callback or the [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) tool returns an invalid result, or when the input stream closes while the request is pending. Before v2.1.216, Claude Code reported these failures as `"user_reject"`. +The `source` value doesn’t indicate which of these sources matched. To find which one refused a call, look for the Safety event with the same `tool_use_id` and read its `category` and `rule_source` attributes. Some refused calls have no safety event. Claude Code also reports `"config"` when the permission prompt request itself fails. For example, that request fails when the Agent SDK’s [`canUseTool`](</docs/en/agent-sdk/typescript#canusetool>) callback or the [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) tool returns an invalid result, or when the input stream closes while the request is pending. * `"hook"`: A `PreToolUse` or `PermissionRequest` hook returned the decision. * `"user_permanent"`: Emitted when the user chose “Yes, and don’t ask again for …” at a permission prompt, which saves an allow rule to their personal settings. In the interactive CLI this is emitted only for that choice itself; later calls that match the saved rule emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the initial choice and later rule matches emit `"user_permanent"`. Treated as an accept. * `"user_temporary"`: Emitted when the user chose “Yes” at a permission prompt for a one-time approval, or chose an option that grants access for the rest of the session on a file edit or read prompt. In the interactive CLI this is emitted only for the choice itself; later calls allowed by that session-scoped grant emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the choice and later matches emit `"user_temporary"`. Treated as an accept. - * `"user_abort"`: Emitted when the user dismissed the permission prompt without answering. In Agent SDK and non-interactive `-p` sessions, this includes interrupting the turn while a `canUseTool` or `--permission-prompt-tool` permission request is pending; before v2.1.216, Claude Code reported that interrupt as `"user_reject"`. Treated as a reject. + * `"user_abort"`: Emitted when the user dismissed the permission prompt without answering. In Agent SDK and non-interactive `-p` sessions, this includes interrupting the turn while a `canUseTool` or `--permission-prompt-tool` permission request is pending. Treated as a reject. * `"user_reject"`: Emitted when the user chose “No” when prompted. In the interactive CLI this is emitted only for that choice itself; calls that match a deny rule in the user’s personal settings emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, calls that match a deny rule in personal settings emit `"user_reject"`. Treated as a reject. * `classifier_verdict`: The auto mode [classifier](</docs/en/permission-modes#how-the-classifier-evaluates-actions>) verdict for the call, or why Claude Code denied the call when none came. Requires Claude Code v2.1.301 or later * `"allow"`: the classifier approved the call
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -438,7 +438,7 @@ When nothing else sets the variable, `host.name` arrives in the resource block, in Desktop SSH sessions and in the CLI on that machine. For where else custom attributes appear, see Multi-team organization support. If the name doesn’t arrive, check for one of these causes: * **You set it on the computer that runs Desktop** : Desktop doesn’t pass a value you set there to the SSH session - * **You exported it in a login file** : only login shells read a file such as `/etc/profile`. A value you `export` there reaches Claude Code that you start from a login shell. It doesn’t reach a Desktop SSH session, because Desktop doesn’t start Claude Code through a login shell. + * **You exported it in`/etc/profile` or another file that only login shells read**: the name arrives when you run `claude` from a login shell, but not in a Desktop SSH session. Desktop doesn’t start Claude Code through a login shell. Set the variable under `env` in the [managed settings file](</docs/en/desktop#managed-settings>) on the remote machine instead. * **A value has a space inside it** : Claude Code then copies none of the keys onto events or datapoints and reports no error. Take the space out of the value. * **Something else already sets the variable** : in a session that the desktop app starts, a variable already set in the launch environment [takes precedence over settings files](</docs/en/settings-reference#how-env-values-interact-with-your-shell>). The [debug log](</docs/en/debug-your-config>) names each ignored variable. When a third-party Desktop deployment names an OTLP endpoint in the environment it provides, that environment carries Desktop’s own `OTEL_RESOURCE_ATTRIBUTES`.
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1360,7 +1360,7 @@ * `pre_tokens`: Approximate token count before compaction * `post_tokens`: Approximate token count after compaction * `error`: Error message when compaction failed - * `precompute_reuse`: Only set when `trigger` is `"manual"` or for an [idle compaction](</docs/en/settings-reference#idlecompaction>), which reports `trigger` as `"auto"`. Auto-compaction can prepare a summary in the background before the context window fills, and this attribute records whether the compaction reused that prepared summary. `"hit"` means it was reused; `"miss_custom_instructions"`, `"miss_hook"`, and `"miss_not_ready"` give the reason a fresh summary was computed instead + * `precompute_reuse`: Only set when `trigger` is `"manual"`, or when `trigger` is `"auto"` for an [idle compaction](</docs/en/settings-reference#idlecompaction>) in an interactive terminal session. Auto-compaction can prepare a summary in the background before the context window fills, and this attribute records whether the compaction reused that prepared summary. `"hit"` means it was reused; `"miss_custom_instructions"`, `"miss_hook"`, and `"miss_not_ready"` give the reason a fresh summary was computed instead ####
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -563,8 +563,10 @@ * `prompt.id`: UUID correlating a user prompt with all subsequent events until the next prompt. See Event correlation attributes. * `workspace.host_paths`: host workspace directories selected in the desktop app, as a string array - * `workflow.run_id`: run identifier, prefixed `wf_`, on the API and tool events emitted by agents that belong to a [Workflow](</docs/en/workflows>) tool run. Filtering events by one `workflow.run_id` reconstructs that run’s API requests and tool results. The identifier covers the agents the workflow script spawns and any agents those spawn in turn, such as skill invocations. It matches the run identifier reported in the Workflow tool result. Absent on all other events. + * `workflow.run_id`: run identifier, prefixed `wf_`, on the API and tool events emitted by agents that belong to a [Workflow](</docs/en/workflows>) tool run. Filtering events by one `workflow.run_id` reconstructs that run’s API requests and tool results. The identifier covers the agents the workflow script spawns and any agents those spawn in turn, such as skill invocations. It matches the run identifier reported in the Workflow tool result. * `workflow.name`: name of the workflow, its script’s `meta.name`, emitted alongside `workflow.run_id`. Built-in workflow names appear verbatim when the run executes the unmodified built-in script. User-authored names, including edited copies of built-in scripts, are replaced with `custom` unless `OTEL_LOG_TOOL_DETAILS=1` is set. + * `agent_id`: identifier of the [subagent](</docs/en/sub-agents>) that raised the event, such as `a3f2c1b4d5e6f7a80`. Events that carry it include a subagent’s API and tool events, its `assistant_response` events, and `subagent_completed` for the finished subagent. Absent on main-session and [in-process teammate](</docs/en/agent-teams#choose-a-display-mode>) events. The subagent’s span `agent_id` is the same value, or adds a label after the leading `a` as in `acompact-3f2c1b4d5e6f7a80`. Requires Claude Code v2.1.310 or later + * `parent_agent_id`: the `agent_id` of the agent that spawned or last resumed the subagent that raised the event. Absent when that agent is the main session. Requires Claude Code v2.1.310 or later #### @@ -737,7 +739,7 @@ `prompt.id`| UUID v4 identifier linking all events produced while processing a single user prompt `event.sequence`| 0-based counter for ordering events, counted per Claude Code process rather than per session `message.uuid`| UUID of the message as persisted in the session transcript, the `~/.claude/projects/*/*.jsonl` files. Present on `assistant_response`, on `api_response_body`, and on `user_prompt` except for command dispatches, which can produce zero or many messages. On `assistant_response` and `api_response_body`, this is the response’s final transcript entry, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.274 or later on `api_response_body` -`request_id`| Server-assigned ID of the API request, read from the `request-id` response header, such as `req_011...`. On a response with no `request-id` header, as on [Amazon Bedrock](</docs/en/amazon-bedrock>), the value comes from the `x-amzn-requestid` header instead. Present on `api_request`, `api_error`, `api_refusal`, `assistant_response`, and `api_response_body` when the response carries either header. Matches the same attribute on the `llm_request` trace span. The `x-amzn-requestid` source requires Claude Code v2.1.282 or later +`request_id`| Server-assigned ID of the API request, read from the `request-id` response header, such as `req_011...`. On a response with no `request-id` header, as on [Amazon Bedrock](</docs/en/amazon-bedrock>), the value comes from the `x-amzn-requestid` header instead. Present on `api_request`, `api_error`, `api_refusal`, `assistant_response`, `api_response_body`, `tool_result`, and `tool_decision` when the response carries either header. Matches the same attribute on the `llm_request` trace span. The `x-amzn-requestid` source requires Claude Code v2.1.282 or later `client_request_id`| Client-generated UUID sent as the `x-client-request-id` request header. Present on `api_request` and `api_error` on first-party API connections; absent on third-party provider backends and when the request was retried through the non-streaming fallback. Pairs a request with its response and remains available for failures such as timeouts that never produced a server `request_id`. Matches the same attribute on the `llm_request` trace span To trace all activity triggered by a single prompt, filter your events by a specific `prompt.id` value. This returns the user_prompt event, any api_request events, and any tool_result events that occurred while processing that prompt. `event.sequence` starts at 0 each time a Claude Code process starts and counts up for the life of that process. It keeps counting across `/clear`, which assigns a new `session.id`. If you [resume a session without forking](</docs/en/how-claude-code-works#resume-or-fork-sessions>), the session keeps its `session.id` but takes its `event.sequence` values from the process that resumed it, so within one session a later event can carry a lower value than an earlier one, or repeat one. To order a session’s events, sort by `event.timestamp` and use `event.sequence` to order events that share a timestamp. For message-level reconstruction, each event class carries a key that matches a field in the session transcript. The transcript entry format is [internal to Claude Code](</docs/en/sessions#where-transcripts-are-stored>) and changes between versions, so a pipeline that joins on these fields can break on any release; treat the joins as version-specific rather than a stable contract: @@ -798,6 +800,7 @@ * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `tool_name`: Name of the tool * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. + * `request_id`: the `request_id` of the API response that contained this tool call, so you can join the call to that response’s API events. Absent when that response had no request ID, or when no API response contained the call. Requires Claude Code v2.1.310 or later * `success`: `"true"` or `"false"` * `duration_ms`: Execution time in milliseconds * `error_type`: Error category string when the tool failed, such as `"Error:ENOENT"` or `"ShellError"` @@ -948,6 +951,7 @@ * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `tool_name`: Name of the tool (for example, “Read”, “Edit”, “Write”, “NotebookEdit”) * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. + * `request_id`: the `request_id` of the API response that contained this tool call, so you can join the call to that response’s API events. Absent when that response had no request ID, or when no API response contained the call. Requires Claude Code v2.1.310 or later * `decision`: Either `"accept"` or `"reject"` * `tool_source`: Always present. The tool’s provenance, as a closed set of CLI-authored values: * `"builtin"`: the CLI’s own tools @@ -991,7 +995,16 @@ * For Skill tool: includes `skill_name` * For Agent tool or legacy Task tool: includes `subagent_type` -If you lower the OpenTelemetry SDK’s `OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT` below the number of attributes on a `tool_decision` event, the SDK drops the attributes that Claude Code set last. The SDK drops `permission_mode` first, `classifier_category` second, and `classifier_verdict` third, and drops the event’s other attributes only after those three. This ordering requires Claude Code v2.1.302 or later. +If you lower the OpenTelemetry SDK’s `OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT` below the number of attributes on a `tool_decision` event, the SDK drops the attributes that Claude Code set last. The SDK drops these before any other attribute, in this order, skipping any the event doesn’t carry: + + 1. `parent_agent_id` + 2. `agent_id` + 3. `request_id` + 4. `permission_mode` + 5. `classifier_category` + 6. `classifier_verdict` + +`permission_mode`, `classifier_category`, and `classifier_verdict` drop in this order on Claude Code v2.1.302 or later. `parent_agent_id`, `agent_id`, and `request_id` require v2.1.310 or later. ####
modified
Show diff (155 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -519,7 +519,7 @@ Attribute telemetry to cloud sessions -By default, metrics and events from a cloud session carry the standard attributes, including `session.id`, `ccr.session.id`, and `organization.id`, so you can filter by session or organization without extra configuration. The `ccr.session.id` value is the session’s `CLAUDE_CODE_REMOTE_SESSION_ID`. To turn it into the session’s transcript URL, see [Link output back to the session](</docs/en/cloud-environments#link-output-back-to-the-session>). To attribute telemetry in more detail, use these options: +By default, metrics and events from a cloud session carry the standard attributes, including `session.id`, `ccr.session.id`, and `organization.id`, so you can filter by session or organization without extra configuration. The `ccr.session.id` value is the session’s `CLAUDE_CODE_REMOTE_SESSION_ID`. To turn it into the session’s transcript URL, see [Link output back to the session](</docs/en/cloud-environments#link-output-back-to-the-session>). To tell cloud sessions apart, group or filter on `ccr.session.id`, not `session.id`. To attribute telemetry in more detail, use these options: * **Identify Claude Tag sessions** : set `OTEL_METRICS_INCLUDE_ENTRYPOINT=true`, as described under Metrics cardinality control. Metrics then carry `app.entrypoint`, whose value is `claude-in-slack` for Claude Tag sessions. * **Add custom attributes** : set `OTEL_RESOURCE_ATTRIBUTES` in the same place you set the other `OTEL_*` variables for those sessions. If you `export` it in the environment’s [setup script](</docs/en/cloud-environments#setup-scripts>) instead, the value doesn’t reach Claude Code: the setup script is a separate Bash script that runs before Claude Code launches, and variables it exports end with it. @@ -542,7 +542,7 @@ Attribute| Description| Controlled By ---|---|--- -`session.id`| Unique session identifier| `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) +`session.id`| Claude Code’s own session ID, which `/clear` replaces| `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) `ccr.session.id`| Cloud session identifier, the value of `CLAUDE_CODE_REMOTE_SESSION_ID`, on sessions that run in a [cloud environment](</docs/en/cloud-environments>)| `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) `app.version`| Current Claude Code version| `OTEL_METRICS_INCLUDE_VERSION` (default: false) `app.entrypoint`| How the session was launched, such as `cli`, `sdk-cli`, `sdk-ts`, `sdk-py`, `claude-vscode`, or `claude-in-slack` for Claude Tag sessions| `OTEL_METRICS_INCLUDE_ENTRYPOINT` (default: false) @@ -744,7 +744,7 @@ * `message.uuid` on `user_prompt`, `assistant_response`, and `api_response_body` * `request_id` on the API events, persisted as `requestId` on the transcript’s assistant entries - * `tool_use_id` on `tool_result` and `tool_decision` events + * `tool_use_id` on `tool_result` and `tool_decision` events, and on `safety_event` events except those for the end of a turn #### @@ -963,7 +963,7 @@ * The auto mode classifier, whose verdict the same event records in `classifier_verdict` * A grant for the rest of the session, given at an earlier permission prompt in the same interactive CLI session * The tool being inherently safe -The `source` value doesn’t indicate which of these sources matched. Claude Code also reports `"config"` when the permission prompt request itself fails. For example, that request fails when the Agent SDK’s [`canUseTool`](</docs/en/agent-sdk/typescript#canusetool>) callback or the [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) tool returns an invalid result, or when the input stream closes while the request is pending. Before v2.1.216, Claude Code reported these failures as `"user_reject"`. +The `source` value doesn’t indicate which of these sources matched. To find which one refused a call, look for the Safety event with the same `tool_use_id` and read its `category` and `rule_source` attributes. Some refused calls have no safety event. Claude Code also reports `"config"` when the permission prompt request itself fails. For example, that request fails when the Agent SDK’s [`canUseTool`](</docs/en/agent-sdk/typescript#canusetool>) callback or the [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) tool returns an invalid result, or when the input stream closes while the request is pending. Before v2.1.216, Claude Code reported these failures as `"user_reject"`. * `"hook"`: A `PreToolUse` or `PermissionRequest` hook returned the decision. * `"user_permanent"`: Emitted when the user chose “Yes, and don’t ask again for …” at a permission prompt, which saves an allow rule to their personal settings. In the interactive CLI this is emitted only for that choice itself; later calls that match the saved rule emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the initial choice and later rule matches emit `"user_permanent"`. Treated as an accept. * `"user_temporary"`: Emitted when the user chose “Yes” at a permission prompt for a one-time approval, or chose an option that grants access for the rest of the session on a file edit or read prompt. In the interactive CLI this is emitted only for the choice itself; later calls allowed by that session-scoped grant emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the choice and later matches emit `"user_temporary"`. Treated as an accept. @@ -979,10 +979,10 @@ * Claude Code approved the call in auto mode without asking the classifier * The user answered the prompt Claude Code showed after [repeated blocks](</docs/en/permission-modes#repeated-block-thresholds>) * In a `-p` run without `--permission-prompt-tool`, Claude Code denied the call after repeated blocks because there was nobody to answer a prompt. That event reports `decision` as `"reject"` and `source` as `"config"` - * `classifier_category` (when `OTEL_LOG_TOOL_DETAILS=1`): The name of the [built-in rule](</docs/en/auto-mode-config#inspect-the-defaults-and-your-effective-config>) the classifier named when it blocked the call, in lowercase with underscores, such as `"data_exfiltration"` for the Data Exfiltration rule. Requires Claude Code v2.1.301 or later. The attribute is present when all of these hold: + * `classifier_category` (when `OTEL_LOG_TOOL_DETAILS=1`): The name of the [built-in rule](</docs/en/auto-mode-config#inspect-the-defaults-and-your-effective-config>) the classifier named when it blocked the call, in lowercase with underscores, such as `"data_exfiltration"` for the Data Exfiltration rule. Requires Claude Code v2.1.301 or later. The attribute is present when both of these hold: * `classifier_verdict` is `"block"` - * Claude Code sent the classifier request itself, rather than using [server-side classifier review](</docs/en/permission-modes#server-side-classifier-review>) * The classifier named exactly one rule, and that rule is a built-in one rather than one you wrote +Before v2.1.302, the attribute was also absent on any block that [server-side classifier review](</docs/en/permission-modes#server-side-classifier-review>) decided. * `permission_mode`: [Permission mode](</docs/en/permission-modes>) active when this call’s permission check began: `"default"`, `"plan"`, `"acceptEdits"`, `"bypassPermissions"`, `"dontAsk"`, or `"auto"`. Manual mode appears as `"default"`. A [subagent](</docs/en/sub-agents#permission-modes>) call reports the subagent’s permission mode rather than the session’s. Requires Claude Code v2.1.301 or later * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters. Same shape as the Tool result event, minus post-execution fields such as `git_commit_id`. Values may differ from `tool_result` for an accepted call if the permission decision rewrites the tool input via `updatedInput`. Use this attribute to see which command was rejected when `decision` is `"reject"`. * For `"sdk_host_builtin_mcp"` tools: `mcp_server_name` and `mcp_tool_name` are included even when `OTEL_LOG_TOOL_DETAILS` is off, because the host application defines these names; without them, a rejected call to one of these built-in servers would be unattributable on the default stream. For user-configured MCP servers, the event’s `tool_name` is always the literal `"mcp_tool"`, and the server and tool names appear only in `tool_parameters` with the flag on; argument content requires the flag everywhere. @@ -992,6 +992,87 @@ * For Agent tool or legacy Task tool: includes `subagent_type` If you lower the OpenTelemetry SDK’s `OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT` below the number of attributes on a `tool_decision` event, the SDK drops the attributes that Claude Code set last. The SDK drops `permission_mode` first, `classifier_category` second, and `classifier_verdict` third, and drops the event’s other attributes only after those three. This ordering requires Claude Code v2.1.302 or later. + +#### + +​ + +Safety event + +Logged when a check refuses a tool call or requires a permission prompt, except for calls without a safety event. Also logged when the [sandbox’s network proxy](</docs/en/sandboxing#network-isolation>) refuses a connection or request, and when a hook blocks a result. Requires Claude Code v2.1.307 or later. The event exports with the other events and has no separate setting. The event’s own attributes hold no command text, file paths, host names, or MCP server and tool names. The record also carries the standard attributes every event has, which can include `workspace.host_paths` and the repository attributes. To see the command or MCP tool behind an event, set `OTEL_LOG_TOOL_DETAILS=1` and read `tool_parameters` on the matching `tool_decision` event. **Event Name** : `claude_code.safety_event` **Attributes** : + + * All standard attributes + * `event.name`: `"safety_event"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes + * `category`: The check or outcome, a category value + * `decision`: `"accept"`, `"reject"`, or `"sent_back"` when a hook blocked a result or turn end + * `decision_source`: Who or what decided, a `tool_decision` `source` value or `"other"` + * `reason_code`: The check’s reason, such as `"rule:policySettings"`, `"mode:dontAsk"`, `"hook:PreToolUse"`, `"classifier:auto-mode"`, `"bashMiss:too-complex"`, or `"unknown"` + * `reason_type`: The check’s reason type, such as `"rule"`, `"subcommandResults"`, `"mode"`, `"hook"`, `"classifier"`, or `"asyncAgent"` + * `rule_source`: Settings source of the rule involved, such as `"policySettings"`, `"userSettings"`, `"projectSettings"`, `"localSettings"`, `"flagSettings"`, `"cliArg"`, or `"session"` + * `grant_scope`: `"once"` or `"session"` for a prompt approved without saving a rule to a settings file + * `circuit_breaker`: The built-in safety check, such as `"dangerousRemoval"`, `"outsideReadsBlocked"`, or `"claudeSettingsFile"` + * `classifier_category`: With `OTEL_LOG_TOOL_DETAILS=1`, the [built-in rule](</docs/en/auto-mode-config#inspect-the-defaults-and-your-effective-config>) behind an auto mode block, such as `"data_exfiltration"` + * `hook_event`: `"pre_tool_use"` for a `PreToolUse` hook, or `"post_tool_use"`, `"post_tool_use_failure"`, `"stop"`, or `"subagent_stop"` on `"hook_review"` events + * `tool_class`: `"bash"` for Bash and [Monitor](</docs/en/tools-reference#monitor-tool>), `"powershell"`, `"file"` for Read, Edit, Write, NotebookEdit, Glob, and Grep, `"web"` for WebFetch and WebSearch, `"mcp"`, or `"other"` + * `tool_name`: The tool’s name, such as `"Bash"` for a built-in tool, or `"mcp_tool"`, `"skill_tool"`, `"dynamic_tool"`, or `"other_tool"` + * `tool_source`: `"builtin"`, `"mcp"`, or `"sdk_host_builtin_mcp"`, as on `tool_decision` + * `permission_mode`: The call’s [permission mode](</docs/en/permission-modes>) when checked: `"default"`, `"plan"`, `"acceptEdits"`, `"bypassPermissions"`, `"dontAsk"`, or `"auto"` + * `tool_use_id`: The call’s ID, as on `tool_decision` and `tool_result` + * `sandbox_violation_count`: How many distinct connections or requests from the call’s command the sandbox’s network proxy refused, `"0"` to `"20"` as a string. Refusals are counted for a sandboxed command that finished in the foreground + * `sandbox_enabled`: `"true"` if [sandboxing](</docs/en/sandboxing>) is on for the session, else `"false"` + +These are the event’s own attributes when a managed-settings deny rule refuses a Bash command: + + { + "event.name": "safety_event", + "category": "managed_policy", + "decision": "reject", + "decision_source": "config", + "reason_code": "rule:policySettings", + "rule_source": "policySettings", + "tool_class": "bash", + "tool_name": "Bash", + "tool_source": "builtin", + "permission_mode": "default", + "tool_use_id": "toolu_01ABC123...", + "sandbox_violation_count": "0", + "sandbox_enabled": "false" + } + +##### Safety event categories + +Value| Check or outcome| Detail attribute +---|---|--- +`"permission_rule"`| A deny or ask [permission rule](</docs/en/permissions#manage-permissions>) outside managed settings| `rule_source` +`"managed_policy"`| A deny or ask rule from [managed settings](</docs/en/permissions#managed-settings>)| `rule_source` +`"permission_mode"`| [`dontAsk`](</docs/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode>) or [plan](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) mode, or a prompt with no category in a session that can’t show prompts, as with [`--permission-prompts none`](</docs/en/headless#turn-off-permission-prompts-in-unattended-runs>)| `reason_code`, `reason_type` +`"hook"`| A hook, such as [`PreToolUse`](</docs/en/hooks#pretooluse>) or [`PermissionRequest`](</docs/en/hooks#permissionrequest>)| `hook_event`, `reason_code` +`"auto_mode_block"`| The auto mode [classifier](</docs/en/permission-modes#how-the-classifier-evaluates-actions>) blocked the call| `classifier_category` +`"auto_mode_no_verdict"`| No usable [classifier verdict](</docs/en/errors#auto-mode-cannot-determine-the-safety-of-an-action>), such as after a failed request| `reason_code` +`"safety_check"`| A built-in safety check, such as for Read, Edit, or Write outside your [working directories](</docs/en/permissions#working-directories>)| `circuit_breaker` +`"static_analysis"`| How a Bash or Monitor command is written, such as one too complex to analyze| `reason_code` +`"sandbox_override"`| The prompt to [run a command outside the sandbox](</docs/en/sandboxing#the-unsandboxed-retry-escape-hatch>)| `reason_code` +`"user_rejected"`| Someone declined or dismissed a prompt that had no category or that only a hook required, or a `canUseTool` callback or `--permission-prompt-tool` tool denied one| `decision_source` +`"sandbox_network"`| The call ran and the [sandbox’s network proxy](</docs/en/sandboxing#network-isolation>) refused a connection or request| `sandbox_violation_count` +`"sandbox_other"`| Like `"sandbox_network"`, but no refused target reads as a host name or IP address| `sandbox_violation_count` +`"hook_review"`| A hook [blocked the call’s result](</docs/en/hooks#posttooluse-decision-control>) or [the end of a turn](</docs/en/hooks#stop-decision-control>)| `hook_event` +`"other"`| A refusal no other value describes| `reason_code` + +To find proxy refusals under any `category`, filter for a `sandbox_violation_count` that is present and isn’t `"0"`. + +##### Calls without a safety event + +To find calls refused because nobody could answer a prompt with no category, look for `tool_decision` events reporting `"reject"` with `source` `"config"` and no safety event sharing their `tool_use_id`. Such refusals happen in a `-p` run with neither [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) nor `--permission-prompts none`. Check calls such as these for a `tool_decision` event, since they have no safety event except `"sandbox_network"`, `"sandbox_other"`, or `"hook_review"` events sent after they run: + + * A call approved at a prompt with no category + * A call that a `canUseTool` callback or `--permission-prompt-tool` tool approved at a prompt only a `PreToolUse` hook required + * An [`AskUserQuestion`](</docs/en/tools-reference#askuserquestion-tool-behavior>) or `ExitPlanMode` call, declined or not + +##### Prompts with no category + +A prompt has no category when no `category` value names its check, such as the `default` mode prompt for an edit inside your working directory. #### @@ -1528,11 +1609,14 @@ Signal| Event| Key attributes ---|---|--- -Tool call allowed or denied, and where the decision came from, such as a rule, a hook, or the user| `tool_decision`| `decision`, `source`, `classifier_verdict`, `permission_mode`, `tool_name`; `tool_parameters` when you set `OTEL_LOG_TOOL_DETAILS=1` +Tool call allowed or denied, and where the decision came from, such as configuration, a hook, or the user| `tool_decision`| `decision`, `source`, `classifier_verdict`, `permission_mode`, `tool_name`; `tool_parameters` when you set `OTEL_LOG_TOOL_DETAILS=1` +Which check refused a tool call or required a permission prompt for it| `safety_event` where `category` names the check, such as `"managed_policy"`, `"permission_rule"`, `"hook"`, or `"auto_mode_block"`. `decision` is `"reject"` for a call that didn’t run. Some calls have no safety event| `category`, `decision`, `reason_code`, `rule_source`, `tool_name`, `tool_use_id` Auto mode classifier allowed or blocked a tool call, or Claude Code denied the call without a classifier verdict| `tool_decision` where `classifier_verdict` is present. For a denial without a verdict, `classifier_verdict` is `"no_verdict"` or `"unavailable"`| `classifier_verdict`, `permission_mode`, `tool_name`; `classifier_category` when you set `OTEL_LOG_TOOL_DETAILS=1` Permission mode escalation| `permission_mode_changed`| `from_mode`, `to_mode`, `trigger` Which permission mode each tool call was checked in, including calls subagents make| `tool_decision`| `permission_mode`, `session.id` Policy hook blocked an action| `hook_execution_complete`| `hook_event`, `num_blocking` +Which tool call a hook refused, and which result or turn end a hook blocked| `safety_event` where `category` is `"hook"` and `decision` is `"reject"` for a refused call, or `category` is `"hook_review"` for a blocked result or turn end| `category`, `decision`, `hook_event`; `tool_use_id` for a tool call +Sandbox’s network proxy refused a connection or request from a Bash or PowerShell command| `safety_event` where `sandbox_violation_count` is present and isn’t `"0"`| `sandbox_violation_count`, `category`, `sandbox_enabled`, `tool_use_id` Login, logout, and authentication failure| `auth`| `action`, `success`, `error_category` MCP server connect or failure| `mcp_server_connection`| `status`, `server_name`, `is_plugin`, `error_code` Plugin installed and its source| `plugin_installed`| `plugin.name`, `marketplace.name`, `marketplace.is_official`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1101,7 +1101,7 @@ * `plugin.scope`: provenance category for the plugin: `"official"`, `"community"`, `"org"`, `"user-local"`, or `"default-bundle"` * `enabled_via`: how the plugin came to be enabled: `"default-enable"`, `"org-policy"`, `"admin-install"`, `"seed-mount"`, or `"user-install"`. The `"admin-install"` value means the plugin is set to required or auto-install for your organization in [**Organization settings > Plugins & skills**](<https://claude.ai/admin-settings/skills?tab=inventory>). Before v2.1.246, Claude Code reported these plugins as `"user-install"` or `"seed-mount"` * `plugin_id_hash`: deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count the distinct third-party plugins loaded across your fleet without recording their names. For [plugins synced from claude.ai](</docs/en/plugins/loading#synced-plugins>), Claude Code hashes the plugin name with the marketplace name that claude.ai reports for the plugin, or with `synced` otherwise. Before v2.1.246, Claude Code didn’t use the marketplace name claude.ai reports in the hash - * `has_hooks`: whether the plugin contributes hooks + * `has_hooks`: whether the plugin contributes hooks, through [hook configuration](</docs/en/plugins/components#hooks>) or as a [mod](</docs/en/plugins/mods/overview#how-a-mod-works>) * `has_mcp`: whether the plugin contributes MCP servers * `host_owned_mcp`: `true` when the SDK host manages this plugin’s MCP connections and Claude Code skipped reading the plugin’s MCP server configuration, `false` otherwise * `skill_path_count`: number of skill directories the plugin declares
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -991,6 +991,8 @@ * For Skill tool: includes `skill_name` * For Agent tool or legacy Task tool: includes `subagent_type` +If you lower the OpenTelemetry SDK’s `OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT` below the number of attributes on a `tool_decision` event, the SDK drops the attributes that Claude Code set last. The SDK drops `permission_mode` first, `classifier_category` second, and `classifier_verdict` third, and drops the event’s other attributes only after those three. This ordering requires Claude Code v2.1.302 or later. + #### ​
modified
Show diff (223 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -111,11 +111,11 @@ `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool content in the `tool.output` span event (default: disabled). Span attributes carry tool content under their own gates. Requires tracing. Content is truncated at the content limit (60 KB by default)| `1` to enable `OTEL_LOG_MANAGED_SETTINGS`| Add the redacted managed settings, and a SHA-256 digest of the settings before redaction, to managed settings resolved events (default: disabled). A value in project or local settings doesn’t turn it on. Requires Claude Code v2.1.274 or later| `1` to enable `OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). 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| `1` for inline bodies truncated at the content limit (60 KB by default), or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event -`CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`| Content limit: the maximum length of content-bearing attributes such as model responses, tool content, system prompts, and raw API bodies, truncation marker included, in UTF-16 code units (default: 61440, i.e. 60 KB). The default is sized for backends that cap attribute values at 64 KB; raise it only if your backend accepts larger values, or lower it to cut telemetry volume. When an OpenTelemetry SDK attribute limit, `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` or one of its logrecord and span variants, is set lower, Claude Code truncates at that smaller value so the `[TRUNCATED ...]` marker stays within the SDK limit. Requires Claude Code v2.1.214 or later| `262144` +`CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`| Content limit: the maximum length of content-bearing attributes such as model responses, tool content, system prompts, and raw API bodies, truncation marker included, in UTF-16 code units (default: 61440, i.e. 60 KB). The default is sized for backends that cap attribute values at 64 KB; raise it only if your backend accepts larger values, or lower it to cut telemetry volume. When an OpenTelemetry SDK attribute limit, `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` or one of its logrecord and span variants, is set lower, Claude Code truncates at that smaller value so the `[TRUNCATED ...]` marker stays within the SDK limit| `262144` `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes)| `900000` -For the `http/protobuf` and `http/json` protocols, Claude Code sends each export request with a `Content-Length` header. Before v2.1.212, Claude Code versions from v2.1.191 onward sent these requests with chunked transfer encoding; Azure Monitor and other endpoints that require a declared length rejected them with `411 Length Required` or `400` errors. +For the `http/protobuf` and `http/json` protocols, Claude Code sends each export request with a `Content-Length` header. ### @@ -168,7 +168,7 @@ `OTEL_EXPORTER_OTLP_TRACES_HEADERS`| Authentication headers for traces, merged with `OTEL_EXPORTER_OTLP_HEADERS`| `Authorization=Bearer token` `OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000` -Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. When tracing is active and Claude Code is connected directly to the Anthropic API, each model request carries a W3C `traceparent` header set to the `claude_code.llm_request` span’s context, and the API’s `traceresponse` header is recorded as a span link. Together these connect Claude Code’s client-side spans to the server-side trace through any compliant intermediary. Outbound HTTP MCP requests carry `traceparent` the same way. The header is not sent to third-party providers. By default, the `traceparent` header on model and HTTP MCP requests is sent only when `ANTHROPIC_BASE_URL` is unset or points at the Anthropic API, since some proxies reject unrecognized headers. The subprocess `TRACEPARENT` variable is controlled by the same switch for consistency. If you run Claude Code through a custom `ANTHROPIC_BASE_URL` proxy and want trace context propagated, set `CLAUDE_CODE_PROPAGATE_TRACEPARENT=1`. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. The inbound trace context also applies to events. In Agent SDK and `-p` sessions with `TRACEPARENT` set, each OTLP event log record carries `trace_id` and `span_id` values that join it to your application’s trace, even when the traces exporter isn’t configured, so your logging backend can correlate events with the rest of the trace. A record emitted while an interaction is active carries the interaction span’s IDs, even when Claude Code emits it outside the span’s async context, such as in a permission prompt callback or for a record buffered during startup and exported later. A record emitted with no active interaction span carries the inbound `TRACEPARENT` IDs directly. Before v2.1.214, records emitted outside the span’s async context carried the inbound `TRACEPARENT` IDs instead of the span’s IDs. Before v2.1.212, event records emitted outside an active span didn’t carry `trace_id` or `span_id`. +Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. When tracing is active and Claude Code is connected directly to the Anthropic API, each model request carries a W3C `traceparent` header set to the `claude_code.llm_request` span’s context, and the API’s `traceresponse` header is recorded as a span link. Together these connect Claude Code’s client-side spans to the server-side trace through any compliant intermediary. Outbound HTTP MCP requests carry `traceparent` the same way. The header is not sent to third-party providers. By default, the `traceparent` header on model and HTTP MCP requests is sent only when `ANTHROPIC_BASE_URL` is unset or points at the Anthropic API, since some proxies reject unrecognized headers. The subprocess `TRACEPARENT` variable is controlled by the same switch for consistency. If you run Claude Code through a custom `ANTHROPIC_BASE_URL` proxy and want trace context propagated, set `CLAUDE_CODE_PROPAGATE_TRACEPARENT=1`. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. The inbound trace context also applies to events. In Agent SDK and `-p` sessions with `TRACEPARENT` set, each OTLP event log record carries `trace_id` and `span_id` values that join it to your application’s trace, even when the traces exporter isn’t configured, so your logging backend can correlate events with the rest of the trace. A record emitted while an interaction is active carries the interaction span’s IDs, even when Claude Code emits it outside the span’s async context, such as in a permission prompt callback or for a record buffered during startup and exported later. A record emitted with no active interaction span carries the inbound `TRACEPARENT` IDs directly. #### @@ -282,10 +282,10 @@ Attribute| Description| Gated by ---|---|--- `duration_ms`| Time spent waiting for the permission decision| -`decision`| `accept` or `reject`| -`source`| Decision source, matching the Tool decision event| - -**`claude_code.tool.execution`** +`decision`| `accept`, `reject`, or `cancelled`, where `cancelled` means Claude Code stopped waiting for a permission decision on the tool call and didn’t run it| +`source`| For an `accept` or `reject`, where the decision came from, such as `config`, `hook`, or `user_temporary`, with the meanings given under the Tool decision event. For a `cancelled`, what ended the wait before any decision was made, such as `user_abort`| + +A `cancelled` decision with `source` `user_abort` means a message needing immediate delivery interrupted the turn while the permission prompt or [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) check was pending. For example, during an auto mode check, the user had a message queued and [sent it immediately](</docs/en/interactive-mode#when-claude-code-sends-what-you-queued>). **`claude_code.tool.execution`** Attribute| Description| Gated by ---|---|--- @@ -736,9 +736,9 @@ ---|--- `prompt.id`| UUID v4 identifier linking all events produced while processing a single user prompt `event.sequence`| 0-based counter for ordering events, counted per Claude Code process rather than per session -`message.uuid`| UUID of the message as persisted in the session transcript, the `~/.claude/projects/*/*.jsonl` files. Present on `assistant_response`, on `api_response_body`, and on `user_prompt` except for command dispatches, which can produce zero or many messages. On `assistant_response` and `api_response_body`, this is the response’s final transcript entry, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.214 or later, or v2.1.274 or later on `api_response_body` +`message.uuid`| UUID of the message as persisted in the session transcript, the `~/.claude/projects/*/*.jsonl` files. Present on `assistant_response`, on `api_response_body`, and on `user_prompt` except for command dispatches, which can produce zero or many messages. On `assistant_response` and `api_response_body`, this is the response’s final transcript entry, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.274 or later on `api_response_body` `request_id`| Server-assigned ID of the API request, read from the `request-id` response header, such as `req_011...`. On a response with no `request-id` header, as on [Amazon Bedrock](</docs/en/amazon-bedrock>), the value comes from the `x-amzn-requestid` header instead. Present on `api_request`, `api_error`, `api_refusal`, `assistant_response`, and `api_response_body` when the response carries either header. Matches the same attribute on the `llm_request` trace span. The `x-amzn-requestid` source requires Claude Code v2.1.282 or later -`client_request_id`| Client-generated UUID sent as the `x-client-request-id` request header. Present on `api_request` and `api_error` on first-party API connections; absent on third-party provider backends and when the request was retried through the non-streaming fallback. Pairs a request with its response and remains available for failures such as timeouts that never produced a server `request_id`. Matches the same attribute on the `llm_request` trace span. Requires Claude Code v2.1.214 or later +`client_request_id`| Client-generated UUID sent as the `x-client-request-id` request header. Present on `api_request` and `api_error` on first-party API connections; absent on third-party provider backends and when the request was retried through the non-streaming fallback. Pairs a request with its response and remains available for failures such as timeouts that never produced a server `request_id`. Matches the same attribute on the `llm_request` trace span To trace all activity triggered by a single prompt, filter your events by a specific `prompt.id` value. This returns the user_prompt event, any api_request events, and any tool_result events that occurred while processing that prompt. `event.sequence` starts at 0 each time a Claude Code process starts and counts up for the life of that process. It keeps counting across `/clear`, which assigns a new `session.id`. If you [resume a session without forking](</docs/en/how-claude-code-works#resume-or-fork-sessions>), the session keeps its `session.id` but takes its `event.sequence` values from the process that resumed it, so within one session a later event can carry a lower value than an earlier one, or repeat one. To order a session’s events, sort by `event.timestamp` and use `event.sequence` to order events that share a timestamp. For message-level reconstruction, each event class carries a key that matches a field in the session transcript. The transcript entry format is [internal to Claude Code](</docs/en/sessions#where-transcripts-are-stored>) and changes between versions, so a pipeline that joins on these fields can break on any release; treat the joins as version-specific rather than a stable contract: @@ -761,7 +761,7 @@ * `prompt_length`: Length of the prompt * `prompt`: Prompt content. Redacted by default. Set `OTEL_LOG_USER_PROMPTS=1` to include it * `prompt_text`: Same value as `prompt`, redacted under the same gate. A backend that stores dotted attribute names as nested objects reads `prompt.id` as `id` inside an object named `prompt` and can lose the prompt string. Read `prompt_text` there instead. Requires Claude Code v2.1.287 or later - * `message.uuid`: UUID of the resulting user message, matching the persisted transcript entry. Absent on command dispatches, which can produce zero or many messages. Requires Claude Code v2.1.214 or later + * `message.uuid`: UUID of the resulting user message, matching the persisted transcript entry. Absent on command dispatches, which can produce zero or many messages. * `command_name`: Command name when the prompt invokes one. Built-in and bundled command names such as `compact` or `debug` are emitted as-is; aliases such as `reset` emit as typed rather than the canonical name. Custom, plugin, and MCP command names collapse to `custom` or `mcp` unless `OTEL_LOG_TOOL_DETAILS=1` is set * `command_source`: Origin of the command when present: `builtin`, `custom`, or `mcp`. Plugin-provided commands report as `custom` @@ -781,7 +781,7 @@ * `response`: Response text, truncated at the content limit (60 KB by default). Redacted to `<REDACTED>` by default. Set `OTEL_LOG_ASSISTANT_RESPONSES=1` to include it. When `OTEL_LOG_ASSISTANT_RESPONSES` is unset, `OTEL_LOG_USER_PROMPTS` controls it instead, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` to keep responses redacted while prompt logging is on * `model`: Model identifier (for example, “claude-sonnet-5”) * `request_id`: API request ID, described under Event correlation attributes - * `message.uuid`: UUID of the response’s final transcript entry. An API response is persisted as one transcript entry per content block; this is the last one, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.214 or later + * `message.uuid`: UUID of the response’s final transcript entry. An API response is persisted as one transcript entry per content block; this is the last one, which the next turn’s `parentUuid` chains from. * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name #### @@ -808,7 +808,7 @@ * `tool_result_size_bytes`: Size of the tool result in bytes * `mcp_server_scope`: MCP server scope identifier (for MCP tools) * `vcs.ref.head.revision`, `vcs.ref.head.name`, `vcs.ref.head.type` (when `OTEL_LOG_TOOL_DETAILS=1`): the commit identity of a successful `git commit` run by the Bash or PowerShell tool. `vcs.ref.head.revision` is the commit SHA, `vcs.ref.head.name` is the branch it was committed on, and `vcs.ref.head.type` is `branch`. The name and type are omitted when the commit was made on a detached HEAD. Requires Claude Code v2.1.269 or later - * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, the `mcp_server_name`/`mcp_tool_name` pair is included even with the flag off, the same host-authored exception as the Tool decision event, requiring Claude Code v2.1.214 or later. The parameters vary by tool: + * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, the `mcp_server_name`/`mcp_tool_name` pair is included even with the flag off, the same host-authored exception as the Tool decision event. The parameters vary by tool: * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, and `dangerouslyDisableSandbox`, plus `git_commit_id` and `git_branch` when a `git commit` command succeeds. `git_commit_id` is the full commit SHA when the commit is the HEAD of the session’s working directory, and git’s abbreviated SHA otherwise. `git_branch` is the branch it was committed on, omitted on a detached HEAD * For the desktop app’s workspace Bash tool, which also reports `tool_name` as `Bash`: includes only `bash_command`, `full_command`, and `timeout` * For MCP tools: includes `mcp_server_name`, `mcp_tool_name` @@ -837,7 +837,7 @@ * `cache_read_tokens`: Number of tokens read from cache * `cache_creation_tokens`: Number of tokens used for cache creation * `request_id`: API request ID, such as `"req_011..."`, described under Event correlation attributes. - * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header; see the event correlation attributes table for when it’s present. Requires Claude Code v2.1.214 or later + * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header; see the event correlation attributes table for when it’s present * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. @@ -861,7 +861,7 @@ * `duration_ms`: Request duration in milliseconds * `attempt`: Number of attempts made, including the initial request. Detect retry exhaustion says when the count starts again * `request_id`: API request ID, such as `"req_011..."`, described under Event correlation attributes. - * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header. Available even when a failure such as a timeout or connection error never produced a server `request_id`; see the event correlation attributes table for when it’s present. Requires Claude Code v2.1.214 or later + * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header. Available even when a failure such as a timeout or connection error never produced a server `request_id`; see the event correlation attributes table for when it’s present. * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. @@ -949,19 +949,43 @@ * `tool_name`: Name of the tool (for example, “Read”, “Edit”, “Write”, “NotebookEdit”) * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. * `decision`: Either `"accept"` or `"reject"` - * `tool_source`: Always present. The tool’s provenance, as a closed set of CLI-authored values. Requires Claude Code v2.1.214 or later + * `tool_source`: Always present. The tool’s provenance, as a closed set of CLI-authored values: * `"builtin"`: the CLI’s own tools * `"mcp"`: MCP servers generally * `"sdk_host_builtin_mcp"`: an in-process server built into Claude Desktop itself, in a session Claude Desktop owns. Claude Desktop owns a session it started from one of its own entrypoints, `claude-desktop`, `claude-desktop-3p`, or `local-agent`, when that session isn’t a nested child; nested sessions, including sessions Claude Code itself spawns, report these servers as `"mcp"` * `source`: Where the decision came from: - * `"config"`: Decided automatically without prompting, based on project settings, allow or deny rules in the user’s personal settings, enterprise managed policy, `--allowedTools` or `--disallowedTools` flags, the active permission mode, a session-scoped grant from an earlier prompt in the same interactive CLI session, or because the tool is inherently safe. The event doesn’t indicate which of these sources matched. Claude Code also reports `"config"` when the permission prompt request itself fails, for example when the Agent SDK’s [`canUseTool`](</docs/en/agent-sdk/typescript#canusetool>) callback or the [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) tool returns an invalid result, or when the input stream closes while the request is pending. Before v2.1.216, Claude Code reported these failures as `"user_reject"`. + * `"config"`: Decided automatically without prompting, by one of these sources: + * Project settings + * Allow or deny rules in the user’s personal settings + * Enterprise managed policy + * `--allowedTools` or `--disallowedTools` flags + * The active permission mode + * The auto mode classifier, whose verdict the same event records in `classifier_verdict` + * A grant for the rest of the session, given at an earlier permission prompt in the same interactive CLI session + * The tool being inherently safe +The `source` value doesn’t indicate which of these sources matched. Claude Code also reports `"config"` when the permission prompt request itself fails. For example, that request fails when the Agent SDK’s [`canUseTool`](</docs/en/agent-sdk/typescript#canusetool>) callback or the [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) tool returns an invalid result, or when the input stream closes while the request is pending. Before v2.1.216, Claude Code reported these failures as `"user_reject"`. * `"hook"`: A `PreToolUse` or `PermissionRequest` hook returned the decision. * `"user_permanent"`: Emitted when the user chose “Yes, and don’t ask again for …” at a permission prompt, which saves an allow rule to their personal settings. In the interactive CLI this is emitted only for that choice itself; later calls that match the saved rule emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the initial choice and later rule matches emit `"user_permanent"`. Treated as an accept. * `"user_temporary"`: Emitted when the user chose “Yes” at a permission prompt for a one-time approval, or chose an option that grants access for the rest of the session on a file edit or read prompt. In the interactive CLI this is emitted only for the choice itself; later calls allowed by that session-scoped grant emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the choice and later matches emit `"user_temporary"`. Treated as an accept. * `"user_abort"`: Emitted when the user dismissed the permission prompt without answering. In Agent SDK and non-interactive `-p` sessions, this includes interrupting the turn while a `canUseTool` or `--permission-prompt-tool` permission request is pending; before v2.1.216, Claude Code reported that interrupt as `"user_reject"`. Treated as a reject. * `"user_reject"`: Emitted when the user chose “No” when prompted. In the interactive CLI this is emitted only for that choice itself; calls that match a deny rule in the user’s personal settings emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, calls that match a deny rule in personal settings emit `"user_reject"`. Treated as a reject. + * `classifier_verdict`: The auto mode [classifier](</docs/en/permission-modes#how-the-classifier-evaluates-actions>) verdict for the call, or why Claude Code denied the call when none came. Requires Claude Code v2.1.301 or later + * `"allow"`: the classifier approved the call + * `"block"`: the classifier blocked the call. A classifier check that fails partway through can also end as `"block"`, so a partial classifier outage can appear as more blocks rather than as `"unavailable"` + * `"no_verdict"`: the check ran but gave [no usable verdict](</docs/en/errors#auto-mode-cannot-determine-the-safety-of-an-action>), so Claude Code denied the call. The denial doesn’t mean the classifier found the call unsafe + * `"unavailable"`: the request to the classifier failed, for example on a rate limit, timeout, or connection error, so Claude Code denied the call. With [server-side classifier review](</docs/en/permission-modes#server-side-classifier-review>), it also marks a call denied because [the server returned no safety verdict](</docs/en/errors#the-server-returned-no-safety-verdict>) +The attribute also appears on plan mode calls when [the classifier reviews commands in plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>). The attribute is absent in these cases: + * An allow or deny [permission rule](</docs/en/permissions#manage-permissions>) decided the call + * Claude Code approved the call in auto mode without asking the classifier + * The user answered the prompt Claude Code showed after [repeated blocks](</docs/en/permission-modes#repeated-block-thresholds>) + * In a `-p` run without `--permission-prompt-tool`, Claude Code denied the call after repeated blocks because there was nobody to answer a prompt. That event reports `decision` as `"reject"` and `source` as `"config"` + * `classifier_category` (when `OTEL_LOG_TOOL_DETAILS=1`): The name of the [built-in rule](</docs/en/auto-mode-config#inspect-the-defaults-and-your-effective-config>) the classifier named when it blocked the call, in lowercase with underscores, such as `"data_exfiltration"` for the Data Exfiltration rule. Requires Claude Code v2.1.301 or later. The attribute is present when all of these hold: + * `classifier_verdict` is `"block"` + * Claude Code sent the classifier request itself, rather than using [server-side classifier review](</docs/en/permission-modes#server-side-classifier-review>) + * The classifier named exactly one rule, and that rule is a built-in one rather than one you wrote + * `permission_mode`: [Permission mode](</docs/en/permission-modes>) active when this call’s permission check began: `"default"`, `"plan"`, `"acceptEdits"`, `"bypassPermissions"`, `"dontAsk"`, or `"auto"`. Manual mode appears as `"default"`. A [subagent](</docs/en/sub-agents#permission-modes>) call reports the subagent’s permission mode rather than the session’s. Requires Claude Code v2.1.301 or later * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters. Same shape as the Tool result event, minus post-execution fields such as `git_commit_id`. Values may differ from `tool_result` for an accepted call if the permission decision rewrites the tool input via `updatedInput`. Use this attribute to see which command was rejected when `decision` is `"reject"`. - * For `"sdk_host_builtin_mcp"` tools: `mcp_server_name` and `mcp_tool_name` are included even when `OTEL_LOG_TOOL_DETAILS` is off, because the host application defines these names; without them, a rejected call to one of these built-in servers would be unattributable on the default stream. For user-configured MCP servers, the event’s `tool_name` is always the literal `"mcp_tool"`, and the server and tool names appear only in `tool_parameters` with the flag on; argument content requires the flag everywhere. Requires Claude Code v2.1.214 or later + * For `"sdk_host_builtin_mcp"` tools: `mcp_server_name` and `mcp_tool_name` are included even when `OTEL_LOG_TOOL_DETAILS` is off, because the host application defines these names; without them, a rejected call to one of these built-in servers would be unattributable on the default stream. For user-configured MCP servers, the event’s `tool_name` is always the literal `"mcp_tool"`, and the server and tool names appear only in `tool_parameters` with the flag on; argument content requires the flag everywhere. * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`. The desktop app’s workspace bash tool also reports `tool_name` as `Bash`, but includes only `bash_command`, `full_command`, and `timeout` * For MCP tools: includes `mcp_server_name`, `mcp_tool_name` * For Skill tool: includes `skill_name` @@ -973,7 +997,7 @@ Permission mode changed event -Logged when the permission mode changes, for example from `Shift+Tab` cycling, exiting plan mode, or an auto mode gate check. **Event Name** : `claude_code.permission_mode_changed` **Attributes** : +Logged when the permission mode changes, for example from `Shift+Tab` cycling, exiting plan mode, or an auto mode gate check. To group tool calls by the permission mode each was checked in, use `permission_mode` on the Tool decision event. **Event Name** : `claude_code.permission_mode_changed` **Attributes** : * All standard attributes * `event.name`: `"permission_mode_changed"` @@ -981,7 +1005,7 @@ * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `from_mode`: The previous permission mode, for example `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, or `"bypassPermissions"` * `to_mode`: The new permission mode - * `trigger`: What caused the change. One of `"shift_tab"`, `"exit_plan_mode"`, `"auto_gate_denied"`, or `"auto_opt_in"`. Absent for some changes, such as when the SDK sets the permission mode through [`setPermissionMode()`](</docs/en/agent-sdk/typescript#query-object>) + * `trigger`: What caused the change, for example `"shift_tab"`, `"exit_plan_mode"`, or `"auto_gate_denied"`. Absent for some changes, such as when the SDK sets the permission mode through [`setPermissionMode()`](</docs/en/agent-sdk/typescript#query-object>) #### @@ -1262,8 +1286,8 @@ * `total_tool_uses`: Number of tool calls the subagent made across the whole run * `duration_ms`: Run time in milliseconds * `model`: The model the subagent was resolved to run - * `final_model`: The model that produced the subagent’s final response, which differs from `model` after a mid-run switch such as a fallback. Requires Claude Code v2.1.212 or later - * `model_swapped`: Whether more than one model served the subagent’s requests. Requires Claude Code v2.1.212 or later + * `final_model`: The model that produced the subagent’s final response, which differs from `model` after a mid-run switch such as a fallback + * `model_swapped`: Whether more than one model served the subagent’s requests * `plugin_id_hash`, `plugin.name`: Present for plugin-provided agents. Official-marketplace plugin names appear verbatim; other plugin names are replaced with `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` is set #### @@ -1394,7 +1418,7 @@ Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, Amazon Bedrock, or Google Cloud’s Agent Platform). -Claude Code counts each streaming response toward the cost and token metrics exactly once, including when a gateway or proxy behind `ANTHROPIC_BASE_URL` streams usage progressively across multiple frames. Before v2.1.214, streams that carried usage in more than one frame inflated `claude_code.cost.usage` and `claude_code.token.usage` by roughly one extra full request per extra frame. +Claude Code counts each streaming response toward the cost and token metrics exactly once, including when a gateway or proxy behind `ANTHROPIC_BASE_URL` streams usage progressively across multiple frames. ### @@ -1416,7 +1440,7 @@ Detect retry exhaustion -Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records the number of attempts. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15. On v2.1.199 or later, you can set `CLAUDE_CODE_RETRY_WATCHDOG` to raise the default and remove the cap. When the request exhausts all retries on a transient error, `attempt` is at most one more than that effective limit: 11 by default. A lower value can still mean the retries ran out: `attempt` starts again from `1` each time Claude Code re-issues the request after a streaming failure. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. +Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records the number of attempts. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15; with [`CLAUDE_CODE_RETRY_WATCHDOG`](</docs/en/env-vars>) set, the default is higher and there is no cap. When the request exhausts all retries on a transient error, `attempt` is at most one more than that effective limit: 11 by default. A lower value can still mean the retries ran out: `attempt` starts again from `1` each time Claude Code re-issues the request after a streaming failure. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. ### @@ -1488,8 +1512,8 @@ Without `OTEL_LOG_TOOL_DETAILS`, these events drop the identifying detail: - * `tool_result`: keeps `mcp_server_scope` and a `tool_name` redacted to the literal `"mcp_tool"` for user-configured servers, omits argument content. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, it also keeps the `mcp_server_name`/`mcp_tool_name` pair inside `tool_parameters`, the same host-authored exception as `tool_decision`, requiring Claude Code v2.1.214 or later - * `tool_decision`: keeps `tool_source` and a `tool_name` redacted to the literal `"mcp_tool"` for user-configured servers, omits argument content. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, it also keeps the `mcp_server_name`/`mcp_tool_name` pair inside `tool_parameters`; `tool_source` and the name pair both require Claude Code v2.1.214 or later + * `tool_result`: keeps `mcp_server_scope` and a `tool_name` redacted to the literal `"mcp_tool"` for user-configured servers, omits argument content. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, it also keeps the `mcp_server_name`/`mcp_tool_name` pair inside `tool_parameters`, the same host-authored exception as `tool_decision` + * `tool_decision`: keeps `tool_source` and a `tool_name` redacted to the literal `"mcp_tool"` for user-configured servers, omits argument content. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, it also keeps the `mcp_server_name`/`mcp_tool_name` pair inside `tool_parameters` * `mcp_server_connection`: omits `server_name` and the error message, but keeps `is_plugin`, `plugin_id_hash`, and `plugin.name`, with non-Anthropic plugin names redacted to the literal `"third-party"`, so plugin-provided servers remain distinguishable without detailed logging ### @@ -1502,8 +1526,10 @@ Signal| Event| Key attributes ---|---|--- -Tool call allowed or denied, and by what| `tool_decision`| `decision`, `source`, `tool_name`, `tool_parameters` +Tool call allowed or denied, and where the decision came from, such as a rule, a hook, or the user| `tool_decision`| `decision`, `source`, `classifier_verdict`, `permission_mode`, `tool_name`; `tool_parameters` when you set `OTEL_LOG_TOOL_DETAILS=1` +Auto mode classifier allowed or blocked a tool call, or Claude Code denied the call without a classifier verdict| `tool_decision` where `classifier_verdict` is present. For a denial without a verdict, `classifier_verdict` is `"no_verdict"` or `"unavailable"`| `classifier_verdict`, `permission_mode`, `tool_name`; `classifier_category` when you set `OTEL_LOG_TOOL_DETAILS=1` Permission mode escalation| `permission_mode_changed`| `from_mode`, `to_mode`, `trigger` +Which permission mode each tool call was checked in, including calls subagents make| `tool_decision`| `permission_mode`, `session.id` Policy hook blocked an action| `hook_execution_complete`| `hook_event`, `num_blocking` Login, logout, and authentication failure| `auth`| `action`, `success`, `error_category` MCP server connect or failure| `mcp_server_connection`| `status`, `server_name`, `is_plugin`, `error_code` @@ -1675,7 +1701,7 @@ * With tracing on, the `claude_code.interaction` span carries the prompt text in its `user_prompt` attribute * Under detailed beta tracing, spans also carry the new user messages, tool results, and system reminders sent with each request, system prompt text, and model output. Content attributes under detailed beta tracing lists each attribute. The `claude_code.system_prompt` event carries the complete system prompt * Assistant response text is not collected by default. Only response length is recorded. To include response text, set `OTEL_LOG_ASSISTANT_RESPONSES=1`. Like all OpenTelemetry data from Claude Code, the response text is sent only to the OTel endpoint you configure, never to Anthropic. When this variable is unset, `OTEL_LOG_USER_PROMPTS` is used as a fallback, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` if you want prompt content without response content in events. Under detailed beta tracing, the `claude_code.llm_request` span still carries model output in `response.model_output`, which follows `OTEL_LOG_USER_PROMPTS` rather than this variable - * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `tool_decision` and `tool_result` carry the `mcp_server_name`/`mcp_tool_name` pair, host-authored names rather than argument content, even with the flag off. The exception requires Claude Code v2.1.214 or later. This data is sent only to the OTEL endpoint you configure, never to Anthropic. Arguments may still contain sensitive values, so configure your telemetry backend to filter or redact these attributes as needed. When enabled: + * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `tool_decision` and `tool_result` carry the `mcp_server_name`/`mcp_tool_name` pair, host-authored names rather than argument content, even with the flag off. This data is sent only to the OTEL endpoint you configure, never to Anthropic. Arguments may still contain sensitive values, so configure your telemetry backend to filter or redact these attributes as needed. When enabled: * `tool_result` and `tool_decision` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names. Fields such as `full_command` are emitted untruncated * `tool_result` events additionally include a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters * `user_prompt` events include the verbatim `command_name` for custom, plugin, and MCP commands
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -684,7 +684,7 @@ Incremented after each API request. **Attributes** : * All standard attributes - * `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`). The `"input"` type excludes tokens read from or written to the prompt cache, which are counted under `"cacheRead"` and `"cacheCreation"` + * `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`). The `"input"` type excludes tokens read from or written to the prompt cache, which are counted under `"cacheRead"` and `"cacheCreation"`. The `"cacheCreation"` type counts cache writes with the five-minute and one-hour [cache lifetimes](</docs/en/prompt-caching#cache-lifetime>) together. * `model`: Model identifier (for example, “claude-sonnet-5”) * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise @@ -981,7 +981,7 @@ * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `from_mode`: The previous permission mode, for example `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, or `"bypassPermissions"` * `to_mode`: The new permission mode - * `trigger`: What caused the change. One of `"shift_tab"`, `"exit_plan_mode"`, `"auto_gate_denied"`, or `"auto_opt_in"`. Absent when the transition originates from the SDK or bridge + * `trigger`: What caused the change. One of `"shift_tab"`, `"exit_plan_mode"`, `"auto_gate_denied"`, or `"auto_opt_in"`. Absent for some changes, such as when the SDK sets the permission mode through [`setPermissionMode()`](</docs/en/agent-sdk/typescript#query-object>) ####
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1,4 +1,6 @@ -Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, events via the logs/events protocol, and optionally distributed traces via the traces protocol. +Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, events via the logs/events protocol, and optionally distributed traces via OpenTelemetry. + +For the Claude API or Managed Agents, see [OpenTelemetry for the Claude API](<https://platform.claude.com/docs/en/manage-claude/opentelemetry>). ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -561,8 +561,8 @@ * `prompt.id`: UUID correlating a user prompt with all subsequent events until the next prompt. See Event correlation attributes. * `workspace.host_paths`: host workspace directories selected in the desktop app, as a string array - * `workflow.run_id`: run identifier, prefixed `wf_`, on the API and tool events emitted by agents that belong to a [Workflow](</docs/en/workflows>) tool run. Filtering events by one `workflow.run_id` reconstructs that run’s API requests and tool results. The identifier covers the agents the workflow script spawns and any agents those spawn in turn, such as skill invocations. It matches the run identifier reported in the Workflow tool result. Absent on all other events. Requires Claude Code v2.1.202 or later - * `workflow.name`: name of the workflow, its script’s `meta.name`, emitted alongside `workflow.run_id`. Built-in workflow names appear verbatim when the run executes the unmodified built-in script. User-authored names, including edited copies of built-in scripts, are replaced with `custom` unless `OTEL_LOG_TOOL_DETAILS=1` is set. Requires Claude Code v2.1.202 or later + * `workflow.run_id`: run identifier, prefixed `wf_`, on the API and tool events emitted by agents that belong to a [Workflow](</docs/en/workflows>) tool run. Filtering events by one `workflow.run_id` reconstructs that run’s API requests and tool results. The identifier covers the agents the workflow script spawns and any agents those spawn in turn, such as skill invocations. It matches the run identifier reported in the Workflow tool result. Absent on all other events. + * `workflow.name`: name of the workflow, its script’s `meta.name`, emitted alongside `workflow.run_id`. Built-in workflow names appear verbatim when the run executes the unmodified built-in script. User-authored names, including edited copies of built-in scripts, are replaced with `custom` unless `OTEL_LOG_TOOL_DETAILS=1` is set. #### @@ -1238,7 +1238,7 @@ * `pre_tokens`: Approximate token count before compaction * `post_tokens`: Approximate token count after compaction * `error`: Error message when compaction failed - * `precompute_reuse`: Only set when `trigger` is `"manual"`. Auto-compaction can prepare a summary in the background before the context window fills, and this attribute records whether `/compact` reused that prepared summary. `"hit"` means it was reused; `"miss_custom_instructions"`, `"miss_hook"`, and `"miss_not_ready"` give the reason a fresh summary was computed instead + * `precompute_reuse`: Only set when `trigger` is `"manual"` or for an [idle compaction](</docs/en/settings-reference#idlecompaction>), which reports `trigger` as `"auto"`. Auto-compaction can prepare a summary in the background before the context window fills, and this attribute records whether the compaction reused that prepared summary. `"hit"` means it was reused; `"miss_custom_instructions"`, `"miss_hook"`, and `"miss_not_ready"` give the reason a fresh summary was computed instead ####
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -418,6 +418,32 @@ ​ +Attribute telemetry to Desktop SSH sessions + +To see which remote machine a [Desktop SSH session](</docs/en/desktop#ssh-sessions>) ran on, name each machine in a custom attribute. Metrics and events don’t name the machine a session ran on. On each remote machine, add `OTEL_RESOURCE_ATTRIBUTES` to the `env` block that turns telemetry on, in the [managed settings file the session reads](</docs/en/desktop#managed-settings>). Write the name out in each machine’s file. Claude Code doesn’t expand the value, so `host.name=$(hostname)` arrives as those characters. The following example names the machine `build-7`: + + { + "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_RESOURCE_ATTRIBUTES": "host.name=build-7" + } + } + +When nothing else sets the variable, `host.name` arrives in the resource block, in Desktop SSH sessions and in the CLI on that machine. For where else custom attributes appear, see Multi-team organization support. If the name doesn’t arrive, check for one of these causes: + + * **You set it on the computer that runs Desktop** : Desktop doesn’t pass a value you set there to the SSH session + * **You exported it in a login file** : only login shells read a file such as `/etc/profile`. A value you `export` there reaches Claude Code that you start from a login shell. It doesn’t reach a Desktop SSH session, because Desktop doesn’t start Claude Code through a login shell. + * **A value has a space inside it** : Claude Code then copies none of the keys onto events or datapoints and reports no error. Take the space out of the value. + * **Something else already sets the variable** : in a session that the desktop app starts, a variable already set in the launch environment [takes precedence over settings files](</docs/en/settings-reference#how-env-values-interact-with-your-shell>). The [debug log](</docs/en/debug-your-config>) names each ignored variable. When a third-party Desktop deployment names an OTLP endpoint in the environment it provides, that environment carries Desktop’s own `OTEL_RESOURCE_ATTRIBUTES`. + +### + +​ + Example configurations Set these environment variables before running `claude`. Each scenario below shows a complete configuration, and each variable is described under Common configuration variables. To confirm a configuration took effect, check your backend for the `claude_code.session.count` metric after starting a session; the Quick start covers logs-only verification and what to check when nothing arrives. For console debugging with a 1-second export interval: @@ -1606,15 +1632,15 @@ All metrics and events are exported with the following resource attributes: - * `service.name`: `claude-code` for terminal sessions, `claude-code-desktop` for sessions started from the Code tab in the [Claude Desktop app](</docs/en/desktop>) - * `service.version`: Current Claude Code version, or the Desktop app version for Code tab sessions + * `service.name`: `claude-code` for terminal sessions, `claude-code-desktop` for local sessions started from the Code tab in the [Claude Desktop app](</docs/en/desktop>) + * `service.version`: Current Claude Code version, or the Desktop app version for local Code tab sessions * `os.type`: Operating system type (for example, `linux`, `darwin`, `windows`) * `os.version`: Operating system version string * `host.arch`: Host architecture (for example, `amd64`, `arm64`) * `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux) * Meter Name: `com.anthropic.claude_code` -If your collector pipelines or dashboards filter on `service.name = claude-code`, add `claude-code-desktop` to the filter to also capture telemetry from Code tab sessions. +If your collector pipelines or dashboards filter on `service.name = claude-code`, add `claude-code-desktop` to the filter to also capture telemetry from local Code tab sessions. ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1080,7 +1080,7 @@ At mention event -Logged when Claude Code resolves an `@`-mention in a prompt. Not every mention emits an event: early-exit paths such as permission denials, oversized files, PDF reference attachments, and directory listing failures return without logging. **Event Name** : `claude_code.at_mention` **Attributes** : +Logged when Claude Code resolves an `@`-mention in a prompt. Not every mention emits an event: early-exit paths such as permission denials, oversized files, PDF reference attachments, and directory listing failures return without logging. Each time Claude Code reads a prompt, it logs at most 100 events with a `mention_type` of `"agent"` and 100 with `"mcp_resource"`. Mentions past either limit still resolve but emit no event. **Event Name** : `claude_code.at_mention` **Attributes** : * All standard attributes * `event.name`: `"at_mention"` @@ -1569,7 +1569,7 @@ ​ -For metrics +Backends for metrics * **Time series databases** : Rate calculations, aggregated metrics * **Columnar stores** : Complex queries, unique user analysis @@ -1579,7 +1579,7 @@ ​ -For events/logs +Backends for events and logs * **Log aggregation systems** : Full-text search, log analysis * **Columnar stores** : Structured event analysis @@ -1589,7 +1589,7 @@ ​ -For traces +Backends for traces Choose a backend that supports distributed trace storage and span correlation:
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -527,7 +527,11 @@ Keys from `OTEL_RESOURCE_ATTRIBUTES`| Custom attributes you set, such as `department` or `team.id`. See Multi-team organization support| `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES` (default: true) `vcs.repository.url.full`, `vcs.owner.name`, `vcs.repository.name`, `vcs.provider.name`| The session repository’s identity, derived from its `origin` remote. See Repository attributes| `OTEL_METRICS_INCLUDE_REPOSITORY` (default: false). Requires Claude Code v2.1.269 or later -In sessions signed in to a [Claude apps gateway](</docs/en/claude-apps-gateway>) through `/login`, the CLI stamps exports with the authenticated identity: `user.id` is the IdP subject, `user.email` is the signed-in email, and `user.groups` carries IdP group membership as a comma-separated string. Each export also carries `identity.source: gateway-oidc`. The gateway identity is applied last, so `user.*` and `identity.*` keys set through `OTEL_RESOURCE_ATTRIBUTES` are ignored on those sessions. For the identity attributes on Claude Desktop and Cowork sessions that connect through a gateway, see the [gateway `telemetry` reference](</docs/en/claude-apps-gateway-config#telemetry>). Events additionally include the following attributes. These are never attached to metrics because they would cause unbounded cardinality: +In sessions signed in to a [Claude apps gateway](</docs/en/claude-apps-gateway>) through `/login`, the CLI stamps exports with the authenticated identity: `user.id` is the IdP subject, `user.email` is the signed-in email, and `user.groups` carries IdP group membership as a comma-separated string. Each export also carries `identity.source: gateway-oidc`. The gateway identity is applied last, so `user.*` and `identity.*` keys set through `OTEL_RESOURCE_ATTRIBUTES` are ignored on those sessions. + +Events that Claude Code logs before a developer signs in don’t carry the gateway identity. When Claude Code opens a session signed out of the gateway, for example after [the gateway ends the sign-in](</docs/en/errors#cloud-gateway-session-expired>), the startup events logged before sign-in carry the anonymous `user.id` and no `identity.source`. These include `managed_settings_resolved`, `plugin_loaded`, and `mcp_server_connection`. + +For the identity attributes on Claude Desktop and Cowork sessions that connect through a gateway, see the [gateway `telemetry` reference](</docs/en/claude-apps-gateway-config#telemetry>). Events additionally include the following attributes. These are never attached to metrics because they would cause unbounded cardinality: * `prompt.id`: UUID correlating a user prompt with all subsequent events until the next prompt. See Event correlation attributes. * `workspace.host_paths`: host workspace directories selected in the desktop app, as a string array @@ -827,7 +831,7 @@ * `error`: Error message * `status_code`: HTTP status code as a number. Absent for non-HTTP errors such as connection failures. * `duration_ms`: Request duration in milliseconds - * `attempt`: Total number of attempts made, including the initial request (`1` means no retries occurred) + * `attempt`: Number of attempts made, including the initial request. Detect retry exhaustion says when the count starts again * `request_id`: API request ID, such as `"req_011..."`, described under Event correlation attributes. * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header. Available even when a failure such as a timeout or connection error never produced a server `request_id`; see the event correlation attributes table for when it’s present. Requires Claude Code v2.1.214 or later * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active @@ -1188,7 +1192,7 @@ * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `plugin_id`: plugin identifier in `<name>@<marketplace>` form * `hook_event`: hook event type that emitted the metrics - * Up to 20 plugin-emitted metric keys. Names match `^[a-z][a-z0-9_]{0,39}$`. Values are boolean or number. + * Up to 20 plugin-emitted metric keys. Names match `^[a-z][a-z0-9_]{0,39}$`. Values are Boolean or number. #### @@ -1250,7 +1254,7 @@ * `appearance_id`: Unique ID linking the events emitted for one survey instance * `survey_type`: Which survey produced the event. `"session"` is the “How is Claude doing?” rating prompt * `response`: The user’s selection on `responded` events - * `enabled_via_override`: `true` when [`CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL`](</docs/en/env-vars>) is set. Emitted as a boolean, not a string. Present on `session` survey events. Filter on this attribute to confirm the override is applied across a fleet + * `enabled_via_override`: `true` when [`CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL`](</docs/en/env-vars>) is set. Emitted as a Boolean, not a string. Present on `session` survey events. Filter on this attribute to confirm the override is applied across a fleet #### @@ -1325,7 +1329,7 @@ * A `permissions.allow`, `permissions.deny`, or `permissions.ask` rule is exported as its tool name with the content redacted, such as `Read([REDACTED])`, when the tool is built into this version of Claude Code or is an `mcp__` reference such as `mcp__jira__create_issue`. Any other rule is exported as `"[REDACTED]"` * Hooks follow the same rules, so fixed-option and numeric fields such as `type` and `timeout` show, while each command, URL, `matcher`, and `if` condition is exported as `"[REDACTED]"` For example, managed settings with `apiKeyHelper`, two `env` variables, and a deny rule are exported as `{"apiKeyHelper":"[REDACTED]","env":{"HTTPS_PROXY":"[REDACTED]","CLAUDE_CODE_ENABLE_TELEMETRY":"[REDACTED]"},"permissions":{"deny":["Read([REDACTED])"]}}`. Claude Code cuts the value at 8 KB of UTF-8, and the cut value isn’t valid JSON - * `managed_settings.settings_truncated` (when `managed_settings.settings` is present): `true` when Claude Code cut `managed_settings.settings` at 8 KB, `false` otherwise. Emitted as a boolean, not a string + * `managed_settings.settings_truncated` (when `managed_settings.settings` is present): `true` when Claude Code cut `managed_settings.settings` at 8 KB, `false` otherwise. Emitted as a Boolean, not a string ## @@ -1384,7 +1388,7 @@ Detect retry exhaustion -Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records the total number of attempts. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15. On v2.1.199 or later, you can set `CLAUDE_CODE_RETRY_WATCHDOG` to raise the default and remove the cap. When the request exhausts all retries on a transient error, `attempt` equals one more than that effective limit: 11 by default, and never more than 16 unless the watchdog is set. A lower value indicates a non-retryable error such as a `400` response, or a cause with its own smaller retry budget. For example, Claude Code retries a failure to load AWS or Google Cloud credentials at most twice. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. +Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records the number of attempts. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15. On v2.1.199 or later, you can set `CLAUDE_CODE_RETRY_WATCHDOG` to raise the default and remove the cap. When the request exhausts all retries on a transient error, `attempt` is at most one more than that effective limit: 11 by default. A lower value can still mean the retries ran out: `attempt` starts again from `1` each time Claude Code re-issues the request after a streaming failure. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -479,7 +479,7 @@ * **Server-managed settings** : add them to the `env` block of your organization’s [server-managed settings](</docs/en/server-managed-settings>). Claude Code fetches those settings at startup wherever [server-managed settings apply](</docs/en/model-config#surface-coverage>), which includes your users’ machines and cloud sessions other than Claude Tag channel sessions. Claude Tag sessions don’t receive your server-managed settings, so this route doesn’t configure them. * **The environment’s variables** : add them to a cloud environment’s [environment variables](</docs/en/cloud-environments#set-environment-variables>) to configure only the sessions that run in that environment. This is the route that reaches Claude Tag sessions. -Anyone who uses an environment can read its variables, so don’t put a credential there, such as a collector token in `OTEL_EXPORTER_OTLP_HEADERS`. An [API credential](</docs/en/cloud-environments#add-api-credentials>) on the environment doesn’t help either, because Claude Code’s own telemetry export is one of the [requests that never get the credential](</docs/en/cloud-environments#requests-that-never-get-the-credential>). If your collector requires a credential, configure the whole export through server-managed settings instead, because when you set a credential there, Claude Code removes endpoint variables set outside managed settings. Keep these constraints in mind when you configure telemetry for cloud sessions: +Anyone who uses an environment can read its variables, so don’t put a credential there, such as a collector token in `OTEL_EXPORTER_OTLP_HEADERS`. A [network secret](</docs/en/cloud-environments#add-network-secrets>) on the environment doesn’t help either, because Claude Code’s own telemetry export is one of the [requests that never get the secret](</docs/en/cloud-environments#requests-that-never-get-the-credential>). If your collector requires a credential, configure the whole export through server-managed settings instead, because when you set a credential there, Claude Code removes endpoint variables set outside managed settings. Keep these constraints in mind when you configure telemetry for cloud sessions: * **Let sessions reach the collector** : Claude Code sends the export through the session’s network, so whether it reaches the host in your `OTEL_EXPORTER_OTLP_ENDPOINT` depends on the environment’s [network access level](</docs/en/cloud-environments#access-levels>). If sessions can’t reach the collector’s domain at the level you chose, [add the domain to the environment’s allowlist](</docs/en/cloud-environments#allow-specific-domains>), because no server-managed setting adds domains to an environment’s network allowlist. * **Claude Tag channels use organization-level environments** : channel sessions run in organization-level environments rather than members’ personal ones, so make the allowlist and any environment-variable changes on the [shared environment](</docs/en/cloud-environments#organization-shared-environments>) set as your organization’s default or pinned to the channel.
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1276,7 +1276,7 @@ * `session_files_deleted`: Number of artifacts the session-files sweep deleted: transcripts plus per-session companion files such as sidecars, recordings, and tool results * `artifacts_deleted`: Total items the sweep deleted across the data directories it covers, including the session files. Some sweeps count a whole removed directory tree as one item and a few cleanup passes don’t contribute to the counter, so treat the value as a floor rather than an exact file count * `files_retained_fresh`: Files inspected and left in place because they’re still within the retention period. Only per-file sweeps count these, so the value is a floor; a nonzero value is the normal steady state - * `files_past_cutoff`: Files older than the retention period that the sweep failed to delete, for example because of a permission error or a file held open. A value above zero means files outlived the configured retention period; zero isn’t proof that none did, because a failed removal of a whole directory counts toward `error_count` instead + * `files_past_cutoff`: Files older than the retention period that the sweep failed to delete, for example because of a permission error or a file held open. The count also includes each stale folder the sweep finds under `skills/synced/` or `plugins/synced/`, whether or not it moves the folder to the trash. Apart from those folders, a value above zero means files outlived the configured retention period; zero isn’t proof that none did, because a failed removal of a whole directory counts toward `error_count` instead * `error_count`: Number of errors the sweep encountered while listing or deleting files #### @@ -1485,6 +1485,57 @@ ​ +Map egress paths to managed controls and events + +The table pairs paths that can carry session content off a machine, plus local retention, with the [managed settings](</docs/en/managed-settings>) keys that restrict them and the events that record them. For what Claude Code itself sends to Anthropic, such as `/feedback` reports, see [Data usage](</docs/en/data-usage>). The names link to their reference entries, which give the values and defaults. + +Path| Managed controls| Events +---|---|--- +Bash and PowerShell commands| [`sandbox.enabled`](</docs/en/settings-reference#sandbox-enabled>), [`sandbox.failIfUnavailable`](</docs/en/settings-reference#sandbox-failifunavailable>), [`sandbox.allowUnsandboxedCommands`](</docs/en/settings-reference#sandbox-allowunsandboxedcommands>), [`sandbox.network.allowManagedDomainsOnly`](</docs/en/settings-reference#sandbox-network-allowmanageddomainsonly>), [`sandbox.network.allowedDomains`](</docs/en/settings-reference#sandbox-network-alloweddomains>)| `tool_decision`, `tool_result` +MCP servers| [`allowedMcpServers`](</docs/en/settings-reference#allowedmcpservers>), [`allowManagedMcpServersOnly`](</docs/en/settings-reference#allowmanagedmcpserversonly>), [`deniedMcpServers`](</docs/en/settings-reference#deniedmcpservers>), [`managed-mcp.json`](</docs/en/managed-mcp>)| `mcp_server_connection`, `tool_decision`, `tool_result` +Hooks| [`allowManagedHooksOnly`](</docs/en/settings-reference#allowmanagedhooksonly>), [`allowedHttpHookUrls`](</docs/en/settings-reference#allowedhttphookurls>)| `hook_registered`, `hook_execution_start`, `hook_execution_complete` +Plugins| [`strictKnownMarketplaces`](</docs/en/settings-reference#strictknownmarketplaces>), [`disableSideloadFlags`](</docs/en/settings-reference#disablesideloadflags>), [`syncClaudeAiPlugins`](</docs/en/settings-reference#syncclaudeaiplugins>), [`syncClaudeAiSkills`](</docs/en/settings-reference#syncclaudeaiskills>)| `plugin_installed`, `plugin_loaded` +[WebFetch](</docs/en/permissions#webfetch>)| [`permissions.deny`](</docs/en/settings-reference#permissions-deny>), [`allowManagedPermissionRulesOnly`](</docs/en/settings-reference#allowmanagedpermissionrulesonly>)| `tool_decision`, `tool_result` +Tools that upload to claude.ai, such as Artifact| `permissions.deny`, [`enableArtifact`](</docs/en/settings-reference#enableartifact>)| `tool_decision`, `tool_result` +Remote Control| [`disableRemoteControl`](</docs/en/settings-reference#disableremotecontrol>)| No dedicated event +Local transcript retention| [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>)| `retention_sweep` + +The `allowedHttpHookUrls`, `managed-mcp.json`, and hook event entries need more than the table shows: + + * **`allowedHttpHookUrls`** : entries merge across settings files, so a developer can add to an empty managed list. `allowManagedHooksOnly` decides which hooks run + * **`managed-mcp.json`** : to turn MCP off, see [Disable MCP entirely](</docs/en/managed-mcp#disable-mcp-entirely>). To confirm Claude Code reads the file, see [Validate the configuration](</docs/en/managed-mcp#validate-the-configuration>) + * **Hook events** : Claude Code logs `hook_execution_start` and `hook_execution_complete` once per hook event, covering every matching hook. `OTEL_LOG_TOOL_DETAILS=1` on its own doesn’t record an HTTP hook’s URL. The hook configuration appears only in `hook_definitions`, which also needs detailed beta tracing + +`OTEL_LOG_TOOL_DETAILS=1` adds command strings, server and tool names, and tool input to these events. That detail can contain the same sensitive content as the session itself, so enable it only when your collector is approved to hold that content. + +### + +​ + +Check the retention sweep + +To give every machine the same retention period, set [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) in [managed settings](</docs/en/managed-settings>). To check that machines run the sweep with that value, collect the `retention_sweep` event. `period_days` and the counters are strings, so cast them to numbers before you compare them. + +What a machine reports| What it means +---|--- +`result` is `"skipped"`| Claude Code paused the sweep. `skip_reason` gives the cause +`used_default` is `"true"`, or `period_days` differs from your managed value| The machine isn’t applying your managed `cleanupPeriodDays` +`error_count` is above zero| The sweep hit errors while it listed or deleted files, so data past the retention period can remain +`files_past_cutoff` is above zero| The sweep failed to delete files past the retention period, or it found stale synced skills and plugins folders. Read it with `error_count` +No event| Not a failure on its own + +A machine that works as intended can go without an event for reasons such as these: + + * **Nobody starts Claude Code** : no sweep runs, and the machine keeps its data until the next launch + * **A session stays open** : Claude Code runs the sweep at most once per session + * **A session ends early** : a sweep that hasn’t finished when the session exits emits nothing, and neither does one that stops on an unexpected error + +The sweep doesn’t cover every path. [Kept until you delete them](</docs/en/claude-directory#kept-until-you-delete-them>) lists what stays, and [Clear local data](</docs/en/claude-directory#clear-local-data>) shows how to remove it. + +### + +​ + Send events to a SIEM Point `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` at your SIEM’s OTLP receiver, or at an OpenTelemetry Collector that forwards to your SIEM’s native ingest API. The following managed-settings example exports events only, with full tool detail enabled for MCP and Bash auditing:
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -104,7 +104,7 @@ `OTEL_METRIC_EXPORT_INTERVAL`| Export interval in milliseconds (default: 60000)| `5000`, `60000` `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable -`OTEL_LOG_ASSISTANT_RESPONSES`| Enable logging of assistant response text on `assistant_response` events (default: disabled). When unset, falls back to the value of `OTEL_LOG_USER_PROMPTS`. Requires Claude Code v2.1.193 or later| `1` to enable, `0` to keep redacted +`OTEL_LOG_ASSISTANT_RESPONSES`| Enable logging of assistant response text on `assistant_response` events (default: disabled). When unset, falls back to the value of `OTEL_LOG_USER_PROMPTS`| `1` to enable, `0` to keep redacted `OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, user-authored workflow names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events, and real agent, skill, plugin, and MCP server and tool names on the cost and token counters (default: disabled). For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `mcp_server_name`/`mcp_tool_name` emit on `tool_decision`/`tool_result` even with the flag off. The exception requires Claude Code v2.1.214 or later| `1` to enable `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool content in the `tool.output` span event (default: disabled). Span attributes carry tool content under their own gates. Requires tracing. Content is truncated at the content limit (60 KB by default)| `1` to enable `OTEL_LOG_MANAGED_SETTINGS`| Add the redacted managed settings, and a SHA-256 digest of the settings before redaction, to managed settings resolved events (default: disabled). A value in project or local settings doesn’t turn it on. Requires Claude Code v2.1.274 or later| `1` to enable @@ -739,7 +739,7 @@ Assistant response event -Logged after each API request that returns text content from the model. Only the response’s text blocks are included; thinking blocks and tool-use blocks are excluded. Requires Claude Code v2.1.193 or later. **Event Name** : `claude_code.assistant_response` **Attributes** : +Logged after each API request that returns text content from the model. Only the response’s text blocks are included; thinking blocks and tool-use blocks are excluded. **Event Name** : `claude_code.assistant_response` **Attributes** : * All standard attributes * `event.name`: `"assistant_response"` @@ -1045,7 +1045,7 @@ * `plugin_id_hash`: deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count the distinct third-party plugins loaded across your fleet without recording their names. For [plugins synced from claude.ai](</docs/en/plugins/loading#synced-plugins>), Claude Code hashes the plugin name with the marketplace name that claude.ai reports for the plugin, or with `synced` otherwise. Before v2.1.246, Claude Code didn’t use the marketplace name claude.ai reports in the hash * `has_hooks`: whether the plugin contributes hooks * `has_mcp`: whether the plugin contributes MCP servers - * `host_owned_mcp`: `true` when the SDK host manages this plugin’s MCP connections and Claude Code skipped reading the plugin’s MCP server configuration, `false` otherwise. Requires Claude Code v2.1.172 or later + * `host_owned_mcp`: `true` when the SDK host manages this plugin’s MCP connections and Claude Code skipped reading the plugin’s MCP server configuration, `false` otherwise * `skill_path_count`: number of skill directories the plugin declares * `command_path_count`: number of command directories the plugin declares * `agent_path_count`: number of agent directories the plugin declares @@ -1208,7 +1208,7 @@ * `pre_tokens`: Approximate token count before compaction * `post_tokens`: Approximate token count after compaction * `error`: Error message when compaction failed - * `precompute_reuse`: Only set when `trigger` is `"manual"`. Auto-compaction can prepare a summary in the background before the context window fills, and this attribute records whether `/compact` reused that prepared summary. `"hit"` means it was reused; `"miss_custom_instructions"`, `"miss_hook"`, and `"miss_not_ready"` give the reason a fresh summary was computed instead. Requires Claude Code v2.1.153 or later + * `precompute_reuse`: Only set when `trigger` is `"manual"`. Auto-compaction can prepare a summary in the background before the context window fills, and this attribute records whether `/compact` reused that prepared summary. `"hit"` means it was reused; `"miss_custom_instructions"`, `"miss_hook"`, and `"miss_not_ready"` give the reason a fresh summary was computed instead #### @@ -1376,7 +1376,7 @@ * Unusual token consumption * High session volume from specific users -All metrics can be segmented by the standard attributes. The `model` attribute is available on `claude_code.token.usage`, `claude_code.cost.usage`, and from v2.1.172, `claude_code.lines_of_code.count`. Per-model breakdowns of commits can only be approximated by joining against the token or cost metrics on `session.id`, since one session can span multiple models. Filter the token or cost side to rows where `query_source` is `"main"` so auxiliary and subagent requests don’t attribute the session’s commits to a model that didn’t make them. +All metrics can be segmented by the standard attributes. The `model` attribute is available on `claude_code.token.usage`, `claude_code.cost.usage`, and `claude_code.lines_of_code.count`. Per-model breakdowns of commits can only be approximated by joining against the token or cost metrics on `session.id`, since one session can span multiple models. Filter the token or cost side to rows where `query_source` is `"main"` so auxiliary and subagent requests don’t attribute the session’s commits to a model that didn’t make them. ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -308,7 +308,24 @@ `num_non_blocking_error`| Count of hooks that failed without blocking| `num_cancelled`| Count of hooks cancelled before completion| -Additional content-bearing attributes such as `new_context`, `system_prompt_preview`, `user_system_prompt`, `tool_input`, and `response.model_output` are emitted only when detailed beta tracing is active. They are not part of the stable span schema.The gate on `new_context` depends on which span carries it, and each copy is truncated at the content limit (60 KB by default). On the `claude_code.tool` span it carries that tool call’s result, whatever the tool, and requires `OTEL_LOG_TOOL_CONTENT=1`. On the `claude_code.interaction` span it carries the user prompt, and on the `claude_code.llm_request` span the new user messages and tool results of that request. Both of those require `OTEL_LOG_USER_PROMPTS=1`.`user_system_prompt` additionally requires `OTEL_LOG_USER_PROMPTS=1`. It carries only the system prompt text you provide via the `systemPrompt` SDK option or `--system-prompt` and `--append-system-prompt` flags, truncated at the content limit (60 KB by default), and is emitted once per session rather than per request. +**Content attributes under detailed beta tracing** + +Additional content-bearing attributes such as `new_context`, `system_reminders`, `system_prompt_preview`, `user_system_prompt`, `tool_input`, and `response.model_output` are emitted only when detailed beta tracing is active. They are not part of the stable span schema. + +These attributes appear on the spans below, and `Gated by` names the variable an attribute needs on top of detailed beta tracing. Values longer than the content limit (60 KB by default) are truncated. + +Attribute| Span| Description| Gated by +---|---|---|--- +`new_context`| `claude_code.interaction`| The user prompt| `OTEL_LOG_USER_PROMPTS` +`new_context`| `claude_code.llm_request`| The new user messages and tool results sent with the request| `OTEL_LOG_USER_PROMPTS` +`system_reminders`| `claude_code.llm_request`| The text of the [system reminders](</docs/en/glossary#system-reminder>) among the request’s new messages| `OTEL_LOG_USER_PROMPTS` +`system_prompt_preview`| `claude_code.llm_request`| First 500 characters of the complete system prompt sent with the request| `OTEL_LOG_USER_PROMPTS` +`user_system_prompt`| `claude_code.llm_request`| Only the system prompt text you provide via the `systemPrompt` SDK option or `--system-prompt` and `--append-system-prompt` flags. Emitted once per session rather than per request| `OTEL_LOG_USER_PROMPTS` +`response.model_output`| `claude_code.llm_request`| Text of the model’s response to the request| `OTEL_LOG_USER_PROMPTS` +`new_context`| `claude_code.tool`| The tool call’s result, whatever the tool| `OTEL_LOG_TOOL_CONTENT` +`tool_input`| `claude_code.tool`| The tool call’s serialized input| `OTEL_LOG_TOOL_DETAILS` + +Under detailed beta tracing with `OTEL_LOG_USER_PROMPTS=1`, Claude Code also emits a `claude_code.system_prompt` event that carries the complete system prompt, truncated at the content limit. It arrives the first time a session sends each distinct system prompt, and again after compaction. ### @@ -711,6 +728,7 @@ * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `prompt_length`: Length of the prompt * `prompt`: Prompt content. Redacted by default. Set `OTEL_LOG_USER_PROMPTS=1` to include it + * `prompt_text`: Same value as `prompt`, redacted under the same gate. A backend that stores dotted attribute names as nested objects reads `prompt.id` as `id` inside an object named `prompt` and can lose the prompt string. Read `prompt_text` there instead. Requires Claude Code v2.1.287 or later * `message.uuid`: UUID of the resulting user message, matching the persisted transcript entry. Absent on command dispatches, which can produce zero or many messages. Requires Claude Code v2.1.214 or later * `command_name`: Command name when the prompt invokes one. Built-in and bundled command names such as `compact` or `debug` are emitted as-is; aliases such as `reset` emit as typed rather than the canonical name. Custom, plugin, and MCP command names collapse to `custom` or `mcp` unless `OTEL_LOG_TOOL_DETAILS=1` is set * `command_source`: Origin of the command when present: `builtin`, `custom`, or `mcp`. Plugin-provided commands report as `custom` @@ -1560,14 +1578,26 @@ * OpenTelemetry export to your backend is opt-in and requires explicit configuration. For Anthropic’s separate operational telemetry and how to disable it, see [Data usage](</docs/en/data-usage#telemetry-services>) * Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below * When authenticated via OAuth, `user.email` is included in telemetry attributes, sent only to the OTel endpoint you configure, never to Anthropic. If this is a concern for your organization, work with your telemetry backend to filter or redact this field - * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1`. Under detailed beta tracing this variable reaches further than prompt text: it also gates the `new_context` span attribute, which carries tool results on the `claude_code.llm_request` span - * Assistant response text is not collected by default. Only response length is recorded. To include response text, set `OTEL_LOG_ASSISTANT_RESPONSES=1`. Like all OpenTelemetry data from Claude Code, the response text is sent only to the OTel endpoint you configure, never to Anthropic. When this variable is unset, `OTEL_LOG_USER_PROMPTS` is used as a fallback, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` if you want prompt content without response content + * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1`. When enabled: + * `user_prompt` events carry the prompt text in two attributes, `prompt` and `prompt_text`. If you drop or mask the event’s prompt text by attribute name in your collector, name both attributes in the rule This OpenTelemetry Collector `attributes` processor deletes both attributes in the pipelines that list it: + + processors: + attributes/drop-prompt-text: + actions: + - key: prompt + action: delete + - key: prompt_text + action: delete + + * With tracing on, the `claude_code.interaction` span carries the prompt text in its `user_prompt` attribute + * Under detailed beta tracing, spans also carry the new user messages, tool results, and system reminders sent with each request, system prompt text, and model output. Content attributes under detailed beta tracing lists each attribute. The `claude_code.system_prompt` event carries the complete system prompt + * Assistant response text is not collected by default. Only response length is recorded. To include response text, set `OTEL_LOG_ASSISTANT_RESPONSES=1`. Like all OpenTelemetry data from Claude Code, the response text is sent only to the OTel endpoint you configure, never to Anthropic. When this variable is unset, `OTEL_LOG_USER_PROMPTS` is used as a fallback, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` if you want prompt content without response content in events. Under detailed beta tracing, the `claude_code.llm_request` span still carries model output in `response.model_output`, which follows `OTEL_LOG_USER_PROMPTS` rather than this variable * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `tool_decision` and `tool_result` carry the `mcp_server_name`/`mcp_tool_name` pair, host-authored names rather than argument content, even with the flag off. The exception requires Claude Code v2.1.214 or later. This data is sent only to the OTEL endpoint you configure, never to Anthropic. Arguments may still contain sensitive values, so configure your telemetry backend to filter or redact these attributes as needed. When enabled: * `tool_result` and `tool_decision` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names. Fields such as `full_command` are emitted untruncated * `tool_result` events additionally include a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters * `user_prompt` events include the verbatim `command_name` for custom, plugin, and MCP commands * The cost and token counters and the `api_request`, `api_error`, and `api_refusal` events carry real agent, skill, plugin, and MCP server and tool names in their attribution attributes - * Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`, with the same truncation as `tool_input` + * The `claude_code.tool` span carries input-derived attributes such as `file_path`. Under detailed beta tracing it also carries a `tool_input` attribute * Tool content is not logged in trace spans by default. 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, and what MCP tools, WebFetch, and WebSearch return, truncated at the content limit (60 KB by default) per attribute. Results from MCP tools, WebFetch, and WebSearch require Claude Code v2.1.283 or later. Tool content also reaches spans through `new_context`, whose gate differs per span. Configure your telemetry backend to filter or redact these attributes as needed * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES` in your shell, user settings, or managed settings. It’s ignored in [project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). The bodies contain the full conversation history, including the system prompt, every prior user and assistant turn, and tool results, so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude Code always redacts Claude’s extended-thinking content from these bodies, regardless of other settings. The value you set determines how Claude Code delivers the bodies: * With `=1`, Claude Code emits `api_request_body` and `api_response_body` log events for each API call. The events’ `body` attribute carries the JSON-serialized payload, truncated at the content limit (60 KB by default)
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -703,7 +703,7 @@ User prompt event -Logged when a user submits a prompt. **Event Name** : `claude_code.user_prompt` **Attributes** : +Logged when a prompt is submitted, including on turns Claude Code starts on its own. **Event Name** : `claude_code.user_prompt` **Attributes** : * All standard attributes * `event.name`: `"user_prompt"`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -221,7 +221,7 @@ `duration_ms`| Wall-clock duration including retries| `ttft_ms`| Time to first token in milliseconds| `first_content_ms`| Time from request start to the first content block of the successful attempt, in milliseconds. Absent on requests that fell back to the non-streaming path. Requires Claude Code v2.1.268 or later| -`input_tokens`| Input token count from the API usage block| +`input_tokens`| Input token count from the API usage block. Excludes tokens read from or written to the prompt cache, which are reported in `cache_read_tokens` and `cache_creation_tokens`| `output_tokens`| Output token count| `cache_read_tokens`| Tokens read from prompt cache| `cache_creation_tokens`| Tokens written to prompt cache| @@ -263,7 +263,7 @@ * A call to any tool other than Read, Edit, Write, Bash, WebFetch, WebSearch, and MCP tools * A Read that returns anything other than file text, such as an image, a PDF, or a re-read of a file whose contents haven’t changed * An Edit or Write call, unless you also set `OTEL_LOG_TOOL_DETAILS=1` - * A WebFetch or WebSearch call that Claude Code moved to the background because you interrupted the turn to [send your queued messages right away](</docs/en/interactive-mode#when-claude-code-sends-what-you-queued>) while the call ran. Claude receives that result later, after the tool span has ended + * A WebFetch or WebSearch call that Claude Code moved to the background while it ran so that a waiting message could reach Claude. The result that arrives later isn’t recorded either. To learn when Claude Code moves a call, see [When Claude Code sends what you queued](</docs/en/interactive-mode#when-claude-code-sends-what-you-queued>) for the terminal and the [`priority` field](</docs/en/agent-sdk/typescript#sdkusermessage>) for Agent SDK sessions The event carries these attributes, each truncated at the content limit (60 KB by default). `Gated by` names the variable an attribute needs on top of `OTEL_LOG_TOOL_CONTENT=1`, and for Edit and Write that variable gates the event itself rather than the attribute. @@ -635,7 +635,7 @@ Incremented after each API request. **Attributes** : * All standard attributes - * `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`) + * `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`). The `"input"` type excludes tokens read from or written to the prompt cache, which are counted under `"cacheRead"` and `"cacheCreation"` * `model`: Model identifier (for example, “claude-sonnet-5”) * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise @@ -782,7 +782,7 @@ * `cost_usd`: Estimated cost in USD * `cost_usd_micros`: Estimated cost in millionths of a US dollar, emitted as an integer * `duration_ms`: Request duration in milliseconds - * `input_tokens`: Number of input tokens + * `input_tokens`: Number of input tokens, excluding tokens read from or written to the prompt cache * `output_tokens`: Number of output tokens * `cache_read_tokens`: Number of tokens read from cache * `cache_creation_tokens`: Number of tokens used for cache creation @@ -1325,7 +1325,7 @@ Metric| Analysis Opportunity ---|--- -`claude_code.token.usage`| Break down by `type` (input/output), user, team, model, `skill.name`, `plugin.name`, or `agent.name` +`claude_code.token.usage`| Break down by token `type`, user, team, model, `skill.name`, `plugin.name`, or `agent.name` `claude_code.session.count`| Track adoption and engagement over time `claude_code.lines_of_code.count`| Measure productivity by tracking code additions and removals, broken down by model `claude_code.commit.count` & `claude_code.pull_request.count`| Understand impact on development workflows @@ -1382,6 +1382,27 @@ * Error patterns by tool type **Performance monitoring** : track API request durations and tool execution times to identify performance bottlenecks. + +### + +​ + +Map input tokens to OpenTelemetry GenAI semantic conventions + +Claude Code exports input token counts as they appear in the API response’s usage block, so these values exclude tokens read from or written to the [prompt cache](</docs/en/prompt-caching>): + + * `input_tokens` on the `claude_code.llm_request` span and the `api_request` event + * The `"input"` type of the `claude_code.token.usage` metric + +Claude Code doesn’t set `gen_ai.usage.*` attributes. The [OpenTelemetry GenAI semantic conventions](<https://github.com/open-telemetry/semantic-conventions-genai>) say `gen_ai.usage.input_tokens` should include tokens read from and written to the cache. To compute that total: + + * From the span or event: add `input_tokens`, `cache_read_tokens`, and `cache_creation_tokens` + * From the `claude_code.token.usage` metric: add its `"input"`, `"cacheRead"`, and `"cacheCreation"` types + +The conventions also define separate attributes for cache reads and cache writes: + + * `cache_read_tokens` maps to `gen_ai.usage.cache_read.input_tokens` + * `cache_creation_tokens` maps to `gen_ai.usage.cache_write.input_tokens`. Older versions of the conventions name the cache write attribute `gen_ai.usage.cache_creation.input_tokens`, so use the name your backend expects. ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1281,7 +1281,8 @@ * `managed_settings.trigger`: `"startup"` for the session-start event, `"change"` when the managed settings or the policy helper’s state changed later in the session, or `"refused"` when a managed settings policy stopped the session. Claude Code sends a `change` event only when an attribute differs from the last event it sent, and a changed setting value counts even when `OTEL_LOG_MANAGED_SETTINGS` is off * `error.type`: why Claude Code stopped the session. Present only on `refused` events: * `"helper_failed"`: a [policy helper run failed](</docs/en/settings-reference#helper-failures>) - * `"policy_invalid"`: the managed settings contain an error that stops Claude Code from starting, or an admin source failed to load, so Claude Code can’t check organization login enforcement + * `"policy_invalid"`: the managed settings contain an error that stops Claude Code from starting, or an admin source failed to load for a reason other than a denied read, so Claude Code can’t check organization login or provider enforcement + * `"provider_not_allowed"`: the session would use an API provider, or send a provider’s traffic to a host, that the managed [`allowedProviders`](</docs/en/settings-reference#allowedproviders>) list doesn’t allow. Requires Claude Code v2.1.285 or later * `"consent_rejected"`: the user rejected the [security approval dialog](</docs/en/server-managed-settings#security-approval-dialogs>) for server-managed settings * `"force_refresh_failed"`: the settings fetch that [`forceRemoteSettingsRefresh`](</docs/en/settings-reference#forceremotesettingsrefresh>) requires failed * `"gateway_rejected"`: a [Claude apps gateway](</docs/en/claude-apps-gateway>) answered the managed settings load with HTTP 403
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -50,7 +50,7 @@ } } -Claude Code ignores the [OpenTelemetry exporter variables](</docs/en/settings-reference#variables-claude-code-ignores-in-env>) in a repository’s `.claude/settings.json` and `.claude/settings.local.json`, so a repository can’t use them to turn telemetry on, choose where it goes, or capture content. Set them in managed settings, or have each developer set them in their shell or `~/.claude/settings.json`. A repository can still turn a signal off by setting its exporter selector, such as `OTEL_LOGS_EXPORTER`, to `none`, unless managed settings, a `--settings` file, or the environment you start Claude Code from sets that variable. Claude Code doesn’t pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool doesn’t inherit Claude Code’s exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry. +In the Claude Desktop app, Code tab sessions read these managed settings from the sources that [reach each kind of Desktop session](</docs/en/desktop#managed-settings>). The OpenTelemetry form for Cowork under **Monitoring** in the admin console’s [Data and privacy settings](<https://claude.ai/admin-settings/data-privacy-controls>) applies to Cowork sessions only, so neither the terminal CLI nor the Code tab exports to a collector you set there. Claude Code ignores the [OpenTelemetry exporter variables](</docs/en/settings-reference#variables-claude-code-ignores-in-env>) in a repository’s `.claude/settings.json` and `.claude/settings.local.json`, so a repository can’t use them to turn telemetry on, choose where it goes, or capture content. Set them in managed settings, or have each developer set them in their shell or `~/.claude/settings.json`. A repository can still turn a signal off by setting its exporter selector, such as `OTEL_LOGS_EXPORTER`, to `none`, unless managed settings, a `--settings` file, or the environment you start Claude Code from sets that variable. Claude Code doesn’t pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool doesn’t inherit Claude Code’s exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry. ### @@ -510,7 +510,7 @@ Keys from `OTEL_RESOURCE_ATTRIBUTES`| Custom attributes you set, such as `department` or `team.id`. See Multi-team organization support| `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES` (default: true) `vcs.repository.url.full`, `vcs.owner.name`, `vcs.repository.name`, `vcs.provider.name`| The session repository’s identity, derived from its `origin` remote. See Repository attributes| `OTEL_METRICS_INCLUDE_REPOSITORY` (default: false). Requires Claude Code v2.1.269 or later -When Claude Code is signed in to a [Claude apps gateway](</docs/en/claude-apps-gateway>), the CLI stamps exports with the authenticated identity from the gateway session: `user.id` is the IdP subject rather than an anonymous installation identifier, `user.email` is the signed-in email, and `user.groups` carries IdP group membership as a comma-separated string. Each export also carries `identity.source: gateway-oidc`. The gateway identity is applied last, so `user.*` and `identity.*` keys set through `OTEL_RESOURCE_ATTRIBUTES` are ignored on gateway sessions. Events additionally include the following attributes. These are never attached to metrics because they would cause unbounded cardinality: +In sessions signed in to a [Claude apps gateway](</docs/en/claude-apps-gateway>) through `/login`, the CLI stamps exports with the authenticated identity: `user.id` is the IdP subject, `user.email` is the signed-in email, and `user.groups` carries IdP group membership as a comma-separated string. Each export also carries `identity.source: gateway-oidc`. The gateway identity is applied last, so `user.*` and `identity.*` keys set through `OTEL_RESOURCE_ATTRIBUTES` are ignored on those sessions. For the identity attributes on Claude Desktop and Cowork sessions that connect through a gateway, see the [gateway `telemetry` reference](</docs/en/claude-apps-gateway-config#telemetry>). Events additionally include the following attributes. These are never attached to metrics because they would cause unbounded cardinality: * `prompt.id`: UUID correlating a user prompt with all subsequent events until the next prompt. See Event correlation attributes. * `workspace.host_paths`: host workspace directories selected in the desktop app, as a string array @@ -1396,7 +1396,7 @@ Attribute actions to users -The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account or, in a [cloud session](</docs/en/claude-code-on-the-web>), when the session’s own credentials carry them, plus `user.id` and the per-session `session.id`. `user.id` is an installation-scoped identifier, except on [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, where it is the IdP subject from the gateway-issued token. In a session a developer starts, MCP tool calls, Bash commands, and file edits are therefore attributed to that developer. Claude Code doesn’t act under a separate service account there; the identity recorded on each event is the developer’s own Claude account, or the developer’s IdP identity on a [Claude apps gateway](</docs/en/claude-apps-gateway>) session. In Claude Tag channel sessions, Claude works as your organization’s [shared identity](</docs/en/cloud-environments#set-the-environment-a-claude-tag-channel-uses>) instead. When Claude Code authenticates with a direct API key, or against Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper. Claude apps gateway sessions need none of this: the CLI stamps the IdP identity automatically, as described in Standard attributes. +The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account or, in a [cloud session](</docs/en/claude-code-on-the-web>), when the session’s own credentials carry them, plus `user.id` and the per-session `session.id`. `user.id` is an installation-scoped identifier, except in sessions signed in to a [Claude apps gateway](</docs/en/claude-apps-gateway>) through `/login`, where it is the IdP subject from the gateway-issued token. In a session a developer starts, MCP tool calls, Bash commands, and file edits are therefore attributed to that developer. Claude Code doesn’t act under a separate service account there; the identity recorded on each event is the developer’s own Claude account, or the developer’s IdP identity on a [Claude apps gateway](</docs/en/claude-apps-gateway>) session. In Claude Tag channel sessions, Claude works as your organization’s [shared identity](</docs/en/cloud-environments#set-the-environment-a-claude-tag-channel-uses>) instead. When Claude Code authenticates with a direct API key, or against Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper. Claude apps gateway sessions need none of this: see Standard attributes for the identity their exports carry. export OTEL_RESOURCE_ATTRIBUTES="enduser.id=jdoe@example.com,enduser.directory_id=S-1-5-21-..."
modified
Show diff (128 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -105,7 +105,7 @@ `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable `OTEL_LOG_ASSISTANT_RESPONSES`| Enable logging of assistant response text on `assistant_response` events (default: disabled). When unset, falls back to the value of `OTEL_LOG_USER_PROMPTS`. Requires Claude Code v2.1.193 or later| `1` to enable, `0` to keep redacted -`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, user-authored workflow names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events (default: disabled). For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `mcp_server_name`/`mcp_tool_name` emit on `tool_decision`/`tool_result` even with the flag off. The exception requires Claude Code v2.1.214 or later| `1` to enable +`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, user-authored workflow names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events, and real agent, skill, plugin, and MCP server and tool names on the cost and token counters (default: disabled). For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `mcp_server_name`/`mcp_tool_name` emit on `tool_decision`/`tool_result` even with the flag off. The exception requires Claude Code v2.1.214 or later| `1` to enable `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool content in the `tool.output` span event (default: disabled). Span attributes carry tool content under their own gates. Requires tracing. Content is truncated at the content limit (60 KB by default)| `1` to enable `OTEL_LOG_MANAGED_SETTINGS`| Add the redacted managed settings, and a SHA-256 digest of the settings before redaction, to managed settings resolved events (default: disabled). A value in project or local settings doesn’t turn it on. Requires Claude Code v2.1.274 or later| `1` to enable `OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). 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| `1` for inline bodies truncated at the content limit (60 KB by default), or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event @@ -140,7 +140,7 @@ Environment Variable| Description| Default Value| Example to Disable ---|---|---|--- -`OTEL_METRICS_INCLUDE_SESSION_ID`| Include session.id attribute in metrics| `true`| `false` +`OTEL_METRICS_INCLUDE_SESSION_ID`| Include session.id and, on cloud sessions, ccr.session.id attributes in metrics| `true`| `false` `OTEL_METRICS_INCLUDE_VERSION`| Include app.version attribute in metrics| `false`| `true` `OTEL_METRICS_INCLUDE_ACCOUNT_UUID`| Include user.account_uuid and user.account_id attributes in metrics| `true`| `false` `OTEL_METRICS_INCLUDE_ENTRYPOINT`| Include app.entrypoint attribute in metrics| `false`| `true` @@ -455,6 +455,36 @@ ​ +Telemetry from cloud sessions and Claude Tag + +[Cloud sessions](</docs/en/claude-code-on-the-web>), including [Claude Tag](<https://claude.com/docs/claude-tag/overview>) channel sessions, run in [cloud environments](</docs/en/cloud-environments>) rather than on your users’ devices, so a managed settings file or shell profile on those devices doesn’t configure their telemetry. For sessions in Anthropic-hosted environments, this section covers where to set the telemetry variables, how to make your collector reachable from the environment, and how to tell cloud and Claude Tag sessions apart in the exported data. To export telemetry from those sessions, set `CLAUDE_CODE_ENABLE_TELEMETRY` and the `OTEL_*` variables, using the same keys as the administrator configuration example, in one of two places: + + * **Server-managed settings** : add them to the `env` block of your organization’s [server-managed settings](</docs/en/server-managed-settings>). Claude Code fetches those settings at startup wherever [server-managed settings apply](</docs/en/model-config#surface-coverage>), which includes your users’ machines and cloud sessions other than Claude Tag channel sessions. Claude Tag sessions don’t receive your server-managed settings, so this route doesn’t configure them. + * **The environment’s variables** : add them to a cloud environment’s [environment variables](</docs/en/cloud-environments#set-environment-variables>) to configure only the sessions that run in that environment. This is the route that reaches Claude Tag sessions. + +Anyone who uses an environment can read its variables, so don’t put a credential there, such as a collector token in `OTEL_EXPORTER_OTLP_HEADERS`. An [API credential](</docs/en/cloud-environments#add-api-credentials>) on the environment doesn’t help either, because Claude Code’s own telemetry export is one of the [requests that never get the credential](</docs/en/cloud-environments#requests-that-never-get-the-credential>). If your collector requires a credential, configure the whole export through server-managed settings instead, because when you set a credential there, Claude Code removes endpoint variables set outside managed settings. Keep these constraints in mind when you configure telemetry for cloud sessions: + + * **Let sessions reach the collector** : Claude Code sends the export through the session’s network, so whether it reaches the host in your `OTEL_EXPORTER_OTLP_ENDPOINT` depends on the environment’s [network access level](</docs/en/cloud-environments#access-levels>). If sessions can’t reach the collector’s domain at the level you chose, [add the domain to the environment’s allowlist](</docs/en/cloud-environments#allow-specific-domains>), because no server-managed setting adds domains to an environment’s network allowlist. + * **Claude Tag channels use organization-level environments** : channel sessions run in organization-level environments rather than members’ personal ones, so make the allowlist and any environment-variable changes on the [shared environment](</docs/en/cloud-environments#organization-shared-environments>) set as your organization’s default or pinned to the channel. + * **Cowork is configured separately** : Cowork sessions don’t receive server-managed settings, as the [surface coverage table](</docs/en/model-config#surface-coverage>) shows, so the server-managed `env` block doesn’t configure their telemetry. + +### + +​ + +Attribute telemetry to cloud sessions + +By default, metrics and events from a cloud session carry the standard attributes, including `session.id`, `ccr.session.id`, and `organization.id`, so you can filter by session or organization without extra configuration. The `ccr.session.id` value is the session’s `CLAUDE_CODE_REMOTE_SESSION_ID`. To turn it into the session’s transcript URL, see [Link output back to the session](</docs/en/cloud-environments#link-output-back-to-the-session>). To attribute telemetry in more detail, use these options: + + * **Identify Claude Tag sessions** : set `OTEL_METRICS_INCLUDE_ENTRYPOINT=true`, as described under Metrics cardinality control. Metrics then carry `app.entrypoint`, whose value is `claude-in-slack` for Claude Tag sessions. + * **Add custom attributes** : set `OTEL_RESOURCE_ATTRIBUTES` in the same place you set the other `OTEL_*` variables for those sessions. If you `export` it in the environment’s [setup script](</docs/en/cloud-environments#setup-scripts>) instead, the value doesn’t reach Claude Code: the setup script is a separate Bash script that runs before Claude Code launches, and variables it exports end with it. + +In Claude Tag channel sessions, Claude works as your organization’s [shared identity](</docs/en/cloud-environments#set-the-environment-a-claude-tag-channel-uses>) rather than as any member, so don’t rely on the `user.*` attributes to identify who tagged Claude. + +## + +​ + Available metrics and events ### @@ -468,8 +498,9 @@ Attribute| Description| Controlled By ---|---|--- `session.id`| Unique session identifier| `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) +`ccr.session.id`| Cloud session identifier, the value of `CLAUDE_CODE_REMOTE_SESSION_ID`, on sessions that run in a [cloud environment](</docs/en/cloud-environments>)| `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) `app.version`| Current Claude Code version| `OTEL_METRICS_INCLUDE_VERSION` (default: false) -`app.entrypoint`| How the session was launched, such as `cli`, `sdk-cli`, `sdk-ts`, `sdk-py`, or `claude-vscode`| `OTEL_METRICS_INCLUDE_ENTRYPOINT` (default: false) +`app.entrypoint`| How the session was launched, such as `cli`, `sdk-cli`, `sdk-ts`, `sdk-py`, `claude-vscode`, or `claude-in-slack` for Claude Tag sessions| `OTEL_METRICS_INCLUDE_ENTRYPOINT` (default: false) `organization.id`| Organization UUID (when authenticated)| Always included when available `user.account_uuid`| Account UUID (when authenticated)| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) `user.account_id`| Account ID in tagged format matching Anthropic admin APIs (when authenticated), such as `user_01BWBeN28...`| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) @@ -492,7 +523,7 @@ Repository attributes -Set `OTEL_METRICS_INCLUDE_REPOSITORY=true` to tag metrics and events with the identity of the session’s repository, so a shared collector can attribute usage per repository. Requires Claude Code v2.1.269 or later. Claude Code derives these attributes once per session from the repository’s `origin` remote. The HTTPS and SSH remotes of one repository produce identical values: +Set `OTEL_METRICS_INCLUDE_REPOSITORY=true` to tag metrics and events with the identity of the session’s repository, so a shared collector can attribute usage per repository. Requires Claude Code v2.1.269 or later. Claude Code derives these attributes once per session from the repository’s `origin` remote. When the HTTPS and SSH remotes of a repository name the same host and the same path, as they do on GitHub, GitLab, and Bitbucket Cloud, both produce identical values: Attribute| Value ---|--- @@ -501,7 +532,7 @@ `vcs.repository.name`| The bare repository name, such as `example-repo` `vcs.provider.name`| `github`, `gitlab`, `bitbucket`, or `gitea` when Claude Code recognizes the remote’s host or URL shape as one of those providers; omitted otherwise -Values are lowercased, and credentials, query strings, and fragments from the remote URL never appear in them. The attributes are omitted when the session has no `origin` remote, when the remote isn’t URL-shaped, or when the only enclosing repository is your home directory. A `vcs.*` key you declare in `OTEL_RESOURCE_ATTRIBUTES` replaces the derived value for that key. If you declare `vcs.repository.url.full`, Claude Code never reads the remote and reports only the keys you declare. The attributes flow only to your own exporters; Anthropic’s telemetry drops every `vcs.*` key. +Values are lowercased, and credentials, query strings, and fragments from the remote URL never appear in them. The attributes are omitted when the session has no `origin` remote, when the remote isn’t URL-shaped, or when the only enclosing repository is your home directory. To get these attributes from a [cloud session](</docs/en/claude-code-on-the-web>), set the telemetry variables, including `OTEL_METRICS_INCLUDE_REPOSITORY`, on its [cloud environment](</docs/en/cloud-environments#set-environment-variables>). Also allow your collector’s domain in the environment’s [network access](</docs/en/cloud-environments#network-access>). A `vcs.*` key you declare in `OTEL_RESOURCE_ATTRIBUTES` replaces the derived value for that key. If you declare `vcs.repository.url.full`, Claude Code never reads the remote and reports only the keys you declare. If HTTPS and SSH clones of one repository report different values, such as on a self-hosted install whose HTTPS clone URL carries a path prefix the SSH URL lacks, declare `vcs.repository.url.full` in `OTEL_RESOURCE_ATTRIBUTES` along with every other `vcs.*` key you want reported. Every clone then reports the identity you declare. The attributes flow only to your own exporters; Anthropic’s telemetry drops every `vcs.*` key. ### @@ -581,18 +612,18 @@ Cost counter -Incremented after each API request. **Attributes** : +Incremented after each API request. The `agent.name`, `skill.name`, `plugin.name`, `mcp_server.name`, and `mcp_tool.name` attributes each redact some names to a `"custom"` or `"third-party"` placeholder by default. If you set `OTEL_LOG_TOOL_DETAILS=1`, they carry the real names instead. Before v2.1.273, the cost and token counters and the `api_request`, `api_error`, and `api_refusal` events carried the redacted values even with `OTEL_LOG_TOOL_DETAILS=1` set. **Attributes** : * All standard attributes * `model`: Model identifier (for example, “claude-sonnet-5”) * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. - * `agent.name`: Subagent type that issued the request. Built-in agent names and agents from official-marketplace plugins appear verbatim. Other user-defined agent names are replaced with `"custom"` unless `OTEL_LOG_TOOL_DETAILS=1` is set. Absent when the request was not issued by a named subagent type. - * `skill.name`: Skill active for the request, set by the Skill tool, a `/` command, or inherited by a spawned subagent. Built-in, bundled, user-defined, and official-marketplace plugin skill names appear verbatim. Third-party plugin skill names are replaced with `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` is set. Absent when no skill is active. - * `plugin.name`: Owning plugin when the active skill or subagent is provided by a plugin. Official-marketplace plugin names appear verbatim. Third-party plugin names are replaced with `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` is set. Absent when neither the skill nor the subagent has an owning plugin. - * `marketplace.name`: Marketplace the owning plugin was installed from. Only emitted for official-marketplace plugins. Absent otherwise. - * `mcp_server.name`: MCP server whose tool result this request consumed. Built-in, claude.ai-proxied, and official-registry server names appear verbatim. User-configured server names are replaced with `"custom"` unless `OTEL_LOG_TOOL_DETAILS=1` is set. Absent when the request consumed no MCP tool result. Before v2.1.222, Claude Code set this attribute on every request after an MCP tool call, not only on requests that consumed a tool result, so dashboards that aggregate it show a step down after you upgrade. + * `agent.name`: Subagent type that issued the request. Built-in agent names and agents from official-marketplace plugins appear verbatim. Other user-defined agent names are replaced with `"custom"`. Absent when the request was not issued by a named subagent type. + * `skill.name`: Skill active for the request, set by the Skill tool or a `/` command, or inherited by a spawned subagent. Built-in, bundled, user-defined, and official-marketplace plugin skill names appear verbatim. Third-party plugin skill names are replaced with `"third-party"`. Absent when no skill is active. + * `plugin.name`: Owning plugin when the active skill or subagent is provided by a plugin. Official-marketplace plugin names appear verbatim. Third-party plugin names are replaced with `"third-party"`. Absent when neither the skill nor the subagent has an owning plugin. + * `marketplace.name`: Marketplace the owning plugin was installed from. Only emitted for official-marketplace plugins, even with `OTEL_LOG_TOOL_DETAILS=1` set. Absent otherwise. + * `mcp_server.name`: MCP server whose tool result this request consumed. Built-in, claude.ai-proxied, and official-registry server names appear verbatim. User-configured server names are replaced with `"custom"`. Absent when the request consumed no MCP tool result. Before v2.1.222, Claude Code set this attribute on every request after an MCP tool call, not only on requests that consumed a tool result, so dashboards that aggregate it show a step down after you upgrade. * `mcp_tool.name`: MCP tool whose result this request consumed, with the same redaction and version behavior as `mcp_server.name`. Absent when the request consumed no MCP tool result. #### @@ -1365,7 +1396,7 @@ Attribute actions to users -The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account or, in a [cloud session](</docs/en/claude-code-on-the-web>), when the session’s own credentials carry them, plus `user.id` and the per-session `session.id`. `user.id` is an installation-scoped identifier, except on [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, where it is the IdP subject from the gateway-issued token. MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code doesn’t act under a separate service account; the identity recorded on each event is the developer’s own Claude account, or the developer’s IdP identity on a [Claude apps gateway](</docs/en/claude-apps-gateway>) session. When Claude Code authenticates with a direct API key, or against Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper. Claude apps gateway sessions need none of this: the CLI stamps the IdP identity automatically, as described in Standard attributes. +The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account or, in a [cloud session](</docs/en/claude-code-on-the-web>), when the session’s own credentials carry them, plus `user.id` and the per-session `session.id`. `user.id` is an installation-scoped identifier, except on [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, where it is the IdP subject from the gateway-issued token. In a session a developer starts, MCP tool calls, Bash commands, and file edits are therefore attributed to that developer. Claude Code doesn’t act under a separate service account there; the identity recorded on each event is the developer’s own Claude account, or the developer’s IdP identity on a [Claude apps gateway](</docs/en/claude-apps-gateway>) session. In Claude Tag channel sessions, Claude works as your organization’s [shared identity](</docs/en/cloud-environments#set-the-environment-a-claude-tag-channel-uses>) instead. When Claude Code authenticates with a direct API key, or against Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper. Claude apps gateway sessions need none of this: the CLI stamps the IdP identity automatically, as described in Standard attributes. export OTEL_RESOURCE_ATTRIBUTES="enduser.id=jdoe@example.com,enduser.directory_id=S-1-5-21-..." @@ -1513,6 +1544,7 @@ * `tool_result` and `tool_decision` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names. Fields such as `full_command` are emitted untruncated * `tool_result` events additionally include a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters * `user_prompt` events include the verbatim `command_name` for custom, plugin, and MCP commands + * The cost and token counters and the `api_request`, `api_error`, and `api_refusal` events carry real agent, skill, plugin, and MCP server and tool names in their attribution attributes * Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`, with the same truncation as `tool_input` * Tool content is not logged in trace spans by default. 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, and what MCP tools, WebFetch, and WebSearch return, truncated at the content limit (60 KB by default) per attribute. Results from MCP tools, WebFetch, and WebSearch require Claude Code v2.1.283 or later. Tool content also reaches spans through `new_context`, whose gate differs per span. Configure your telemetry backend to filter or redact these attributes as needed * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES` in your shell, user settings, or managed settings. It’s ignored in [project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). The bodies contain the full conversation history, including the system prompt, every prior user and assistant turn, and tool results, so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude Code always redacts Claude’s extended-thinking content from these bodies, regardless of other settings. The value you set determines how Claude Code delivers the bodies:
modified
Show diff (124 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -29,7 +29,7 @@ # 6. Run Claude Code claude -To verify a setup that exports metrics, check your backend for the `claude_code.session.count` metric, which Claude Code emits when a session starts. To verify a logs-only setup, submit a prompt and check for the `claude_code.user_prompt` event. If nothing arrives, run `claude --debug` and check the debug log. Claude Code reports failures from the exporters you configure as `[3P telemetry]` errors, where 3P means third-party. Lines prefixed `[Anthropic telemetry]` describe [Anthropic’s separate operational telemetry](</docs/en/data-usage#telemetry-services>) and don’t indicate a problem with your setup. For full configuration options, see the [OpenTelemetry specification](<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options>). +To verify a setup that exports metrics, check your backend for the `claude_code.session.count` metric, which Claude Code emits when a session starts. To verify a logs-only setup, submit a prompt and check for the `claude_code.user_prompt` event. If nothing arrives, start Claude Code with `claude --debug-file <path>` and check the log it writes to that path. Claude Code reports failures from the exporters you configure as `[3P telemetry]` errors, where 3P means third-party. Lines prefixed `[Anthropic telemetry]` describe [Anthropic’s separate operational telemetry](</docs/en/data-usage#telemetry-services>) and don’t indicate a problem with your setup. For full configuration options, see the [OpenTelemetry specification](<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options>). ## @@ -58,7 +58,7 @@ How managed settings lock the OTLP destination -When you set an `OTEL_EXPORTER_OTLP_*` variable in managed settings, Claude Code removes conflicting developer-set variables at startup and logs a warning you can see with `claude --debug`. What it removes depends on which variable you set: +When you set an `OTEL_EXPORTER_OTLP_*` variable in managed settings, Claude Code removes conflicting developer-set variables at startup and logs a warning in the debug log. What it removes depends on which variable you set: * **Endpoints** : when you set `OTEL_EXPORTER_OTLP_ENDPOINT`, Claude Code removes every developer-set per-signal endpoint. Developers can’t point one signal at a different collector, so you don’t need to also set the per-signal endpoint variables in managed settings. * **Protocols** : when you set `OTEL_EXPORTER_OTLP_PROTOCOL`, Claude Code removes every developer-set per-signal protocol. @@ -225,7 +225,7 @@ `output_tokens`| Output token count| `cache_read_tokens`| Tokens read from prompt cache| `cache_creation_tokens`| Tokens written to prompt cache| -`request_id`| Anthropic API request ID from the `request-id` response header| +`request_id`| API request ID. Same value as the `request_id` event correlation attribute| `gen_ai.response.id`| Same value as `request_id`. OpenTelemetry GenAI semantic convention| `client_request_id`| Client-generated `x-client-request-id` of the final attempt| `attempt`| Total attempts made for this request| @@ -258,18 +258,19 @@ `skill_name`| Skill name for the Skill tool| `OTEL_LOG_TOOL_DETAILS` `subagent_type`| Subagent type for the Agent tool or legacy Task tool| `OTEL_LOG_TOOL_DETAILS` -**`tool.output` span event on `claude_code.tool`** If you set `OTEL_LOG_TOOL_CONTENT=1`, Read and Bash calls can record a `tool.output` span event on the `claude_code.tool` span. Edit and Write calls record one only when you also set `OTEL_LOG_TOOL_DETAILS=1`. That variable isn’t scoped to those two tools, so check its row in the configuration table for the arguments it adds elsewhere. Claude Code writes this event from a tool call’s successful return, so a call that raises an error records nothing, whatever the tool. Among the calls that do return, it records no `tool.output` event for: - - * A call to any tool other than Read, Edit, Write, and Bash, including MCP tools and WebFetch +**`tool.output` span event on `claude_code.tool`** If you set `OTEL_LOG_TOOL_CONTENT=1`, Read and Bash calls can record a `tool.output` span event on the `claude_code.tool` span. Edit and Write calls record one only when you also set `OTEL_LOG_TOOL_DETAILS=1`. That variable isn’t scoped to those two tools, so check its row in the configuration table for the arguments it adds elsewhere. MCP tools, WebFetch, and WebSearch record this event too, on Claude Code v2.1.283 or later. Claude Code writes this event from a tool call’s successful return, so a call that raises an error records nothing, whatever the tool. Among the calls that do return, it records no `tool.output` event for: + + * A call to any tool other than Read, Edit, Write, Bash, WebFetch, WebSearch, and MCP tools * A Read that returns anything other than file text, such as an image, a PDF, or a re-read of a file whose contents haven’t changed * An Edit or Write call, unless you also set `OTEL_LOG_TOOL_DETAILS=1` + * A WebFetch or WebSearch call that Claude Code moved to the background because you interrupted the turn to [send your queued messages right away](</docs/en/interactive-mode#when-claude-code-sends-what-you-queued>) while the call ran. Claude receives that result later, after the tool span has ended The event carries these attributes, each truncated at the content limit (60 KB by default). `Gated by` names the variable an attribute needs on top of `OTEL_LOG_TOOL_CONTENT=1`, and for Edit and Write that variable gates the event itself rather than the attribute. Attribute| Description| Gated by ---|---|--- `content`| Text the Read tool returned, or the text a Write call was asked to write| `OTEL_LOG_TOOL_DETAILS` for the Write tool -`output`| Combined output of a Bash command, with stderr interleaved into stdout| +`output`| For the Bash tool, the command’s combined output, with stderr interleaved into stdout. For an MCP tool, WebFetch, or WebSearch, the result the tool returned: text blocks joined by newlines, with an image or document replaced by a placeholder such as `[image]`| `diff`| Structured patch the Edit tool applied| `OTEL_LOG_TOOL_DETAILS` `file_path`| Target file path for the Read, Edit, and Write tools, repeating the span attribute of the same name| `OTEL_LOG_TOOL_DETAILS` `bash_command`| Command string for the Bash tool| `OTEL_LOG_TOOL_DETAILS` @@ -656,6 +657,7 @@ `prompt.id`| UUID v4 identifier linking all events produced while processing a single user prompt `event.sequence`| 0-based counter for ordering events, counted per Claude Code process rather than per session `message.uuid`| UUID of the message as persisted in the session transcript, the `~/.claude/projects/*/*.jsonl` files. Present on `assistant_response`, on `api_response_body`, and on `user_prompt` except for command dispatches, which can produce zero or many messages. On `assistant_response` and `api_response_body`, this is the response’s final transcript entry, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.214 or later, or v2.1.274 or later on `api_response_body` +`request_id`| Server-assigned ID of the API request, read from the `request-id` response header, such as `req_011...`. On a response with no `request-id` header, as on [Amazon Bedrock](</docs/en/amazon-bedrock>), the value comes from the `x-amzn-requestid` header instead. Present on `api_request`, `api_error`, `api_refusal`, `assistant_response`, and `api_response_body` when the response carries either header. Matches the same attribute on the `llm_request` trace span. The `x-amzn-requestid` source requires Claude Code v2.1.282 or later `client_request_id`| Client-generated UUID sent as the `x-client-request-id` request header. Present on `api_request` and `api_error` on first-party API connections; absent on third-party provider backends and when the request was retried through the non-streaming fallback. Pairs a request with its response and remains available for failures such as timeouts that never produced a server `request_id`. Matches the same attribute on the `llm_request` trace span. Requires Claude Code v2.1.214 or later To trace all activity triggered by a single prompt, filter your events by a specific `prompt.id` value. This returns the user_prompt event, any api_request events, and any tool_result events that occurred while processing that prompt. `event.sequence` starts at 0 each time a Claude Code process starts and counts up for the life of that process. It keeps counting across `/clear`, which assigns a new `session.id`. If you [resume a session without forking](</docs/en/how-claude-code-works#resume-or-fork-sessions>), the session keeps its `session.id` but takes its `event.sequence` values from the process that resumed it, so within one session a later event can carry a lower value than an earlier one, or repeat one. To order a session’s events, sort by `event.timestamp` and use `event.sequence` to order events that share a timestamp. For message-level reconstruction, each event class carries a key that matches a field in the session transcript. The transcript entry format is [internal to Claude Code](</docs/en/sessions#where-transcripts-are-stored>) and changes between versions, so a pipeline that joins on these fields can break on any release; treat the joins as version-specific rather than a stable contract: @@ -697,7 +699,7 @@ * `response_length`: Length of the response text in characters * `response`: Response text, truncated at the content limit (60 KB by default). Redacted to `<REDACTED>` by default. Set `OTEL_LOG_ASSISTANT_RESPONSES=1` to include it. When `OTEL_LOG_ASSISTANT_RESPONSES` is unset, `OTEL_LOG_USER_PROMPTS` controls it instead, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` to keep responses redacted while prompt logging is on * `model`: Model identifier (for example, “claude-sonnet-5”) - * `request_id`: Anthropic API request ID from the response’s `request-id` header. Present only when the API returns one + * `request_id`: API request ID, described under Event correlation attributes * `message.uuid`: UUID of the response’s final transcript entry. An API response is persisted as one transcript entry per content block; this is the last one, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.214 or later * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name @@ -753,7 +755,7 @@ * `output_tokens`: Number of output tokens * `cache_read_tokens`: Number of tokens read from cache * `cache_creation_tokens`: Number of tokens used for cache creation - * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. + * `request_id`: API request ID, such as `"req_011..."`, described under Event correlation attributes. * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header; see the event correlation attributes table for when it’s present. Requires Claude Code v2.1.214 or later * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name @@ -777,7 +779,7 @@ * `status_code`: HTTP status code as a number. Absent for non-HTTP errors such as connection failures. * `duration_ms`: Request duration in milliseconds * `attempt`: Total number of attempts made, including the initial request (`1` means no retries occurred) - * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. + * `request_id`: API request ID, such as `"req_011..."`, described under Event correlation attributes. * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header. Available even when a failure such as a timeout or connection error never produced a server `request_id`; see the event correlation attributes table for when it’s present. Requires Claude Code v2.1.214 or later * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name @@ -797,7 +799,7 @@ * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `model`: Model identifier from the request - * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. + * `request_id`: API request ID, such as `"req_011..."`, described under Event correlation attributes. * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name. See `api_request` for definitions. * `speed`: Either `"fast"` when [Fast mode](</docs/en/fast-mode>) is active, or `"normal"` * `attempt`: Retry attempt number. The first attempt is `1`. @@ -846,7 +848,7 @@ * `body_truncated`: `"true"` when inline truncation occurred. Absent in file mode and when no truncation occurred. * `model`: Model identifier * `query_source`: Subsystem that issued the request - * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. + * `request_id`: API request ID, such as `"req_011..."`, described under Event correlation attributes. * `request_body_id`: The `request_body_id` of the `api_request_body` event that this response answers. Requires Claude Code v2.1.274 or later * `message.id`: Message ID the API assigned to the response, the `id` field of the response body. Requires Claude Code v2.1.274 or later * `message.uuid`: UUID of the response’s final transcript entry. Together with `request_body_id`, it links a transcript message to the request and response bodies behind it. Requires Claude Code v2.1.274 or later @@ -1427,7 +1429,7 @@ } } -To confirm events arrive, submit a prompt in a session running under this configuration and check your SIEM for the `claude_code.user_prompt` event. If nothing arrives, run `claude --debug` and check the debug log for `[3P telemetry]` export errors. +To confirm events arrive, submit a prompt in a session running under this configuration and check your SIEM for the `claude_code.user_prompt` event. If nothing arrives, start Claude Code with `claude --debug-file <path>` and check that log for `[3P telemetry]` export errors. ## @@ -1512,7 +1514,7 @@ * `tool_result` events additionally include a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters * `user_prompt` events include the verbatim `command_name` for custom, plugin, and MCP commands * Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`, with the same truncation as `tool_input` - * Tool content is not logged in trace spans by default. 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 and Bash command output, truncated at the content limit (60 KB by default) per attribute. Tool content also reaches spans through `new_context`, whose gate differs per span. Configure your telemetry backend to filter or redact these attributes as needed + * Tool content is not logged in trace spans by default. 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, and what MCP tools, WebFetch, and WebSearch return, truncated at the content limit (60 KB by default) per attribute. Results from MCP tools, WebFetch, and WebSearch require Claude Code v2.1.283 or later. Tool content also reaches spans through `new_context`, whose gate differs per span. Configure your telemetry backend to filter or redact these attributes as needed * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES` in your shell, user settings, or managed settings. It’s ignored in [project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). The bodies contain the full conversation history, including the system prompt, every prior user and assistant turn, and tool results, so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude Code always redacts Claude’s extended-thinking content from these bodies, regardless of other settings. The value you set determines how Claude Code delivers the bodies: * With `=1`, Claude Code emits `api_request_body` and `api_response_body` log events for each API call. The events’ `body` attribute carries the JSON-serialized payload, truncated at the content limit (60 KB by default) * With `=file:<dir>`, Claude Code writes untruncated bodies to `.request.json` and `.response.json` files under that directory, and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. For each successful response, Claude Code also appends one line to `index.jsonl` in that directory, linking the response file to the request file that produced it and to the transcript message it became. Each line holds no message content, and the API response body event section lists its fields. The index file requires Claude Code v2.1.274 or later
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -50,7 +50,7 @@ } } -Claude Code doesn’t pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool doesn’t inherit Claude Code’s exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry. +Claude Code ignores the [OpenTelemetry exporter variables](</docs/en/settings-reference#variables-claude-code-ignores-in-env>) in a repository’s `.claude/settings.json` and `.claude/settings.local.json`, so a repository can’t use them to turn telemetry on, choose where it goes, or capture content. Set them in managed settings, or have each developer set them in their shell or `~/.claude/settings.json`. A repository can still turn a signal off by setting its exporter selector, such as `OTEL_LOGS_EXPORTER`, to `none`, unless managed settings, a `--settings` file, or the environment you start Claude Code from sets that variable. Claude Code doesn’t pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool doesn’t inherit Claude Code’s exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry. ### @@ -587,11 +587,11 @@ * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. - * `agent.name`: Subagent type that issued the request. Built-in agent names and agents from official-marketplace plugins appear verbatim. Other user-defined agent names are replaced with `"custom"`. Absent when the request was not issued by a named subagent type. - * `skill.name`: Skill active for the request, set by the Skill tool, a `/` command, or inherited by a spawned subagent. Built-in, bundled, user-defined, and official-marketplace plugin skill names appear verbatim. Third-party plugin skill names are replaced with `"third-party"`. Absent when no skill is active. - * `plugin.name`: Owning plugin when the active skill or subagent is provided by a plugin. Official-marketplace plugin names appear verbatim. Third-party plugin names are replaced with `"third-party"`. Absent when neither the skill nor the subagent has an owning plugin. + * `agent.name`: Subagent type that issued the request. Built-in agent names and agents from official-marketplace plugins appear verbatim. Other user-defined agent names are replaced with `"custom"` unless `OTEL_LOG_TOOL_DETAILS=1` is set. Absent when the request was not issued by a named subagent type. + * `skill.name`: Skill active for the request, set by the Skill tool, a `/` command, or inherited by a spawned subagent. Built-in, bundled, user-defined, and official-marketplace plugin skill names appear verbatim. Third-party plugin skill names are replaced with `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` is set. Absent when no skill is active. + * `plugin.name`: Owning plugin when the active skill or subagent is provided by a plugin. Official-marketplace plugin names appear verbatim. Third-party plugin names are replaced with `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` is set. Absent when neither the skill nor the subagent has an owning plugin. * `marketplace.name`: Marketplace the owning plugin was installed from. Only emitted for official-marketplace plugins. Absent otherwise. - * `mcp_server.name`: MCP server whose tool result this request consumed. Built-in, claude.ai-proxied, and official-registry server names appear verbatim. User-configured server names are replaced with `"custom"`. Absent when the request consumed no MCP tool result. Before v2.1.222, Claude Code set this attribute on every request after an MCP tool call, not only on requests that consumed a tool result, so dashboards that aggregate it show a step down after you upgrade. + * `mcp_server.name`: MCP server whose tool result this request consumed. Built-in, claude.ai-proxied, and official-registry server names appear verbatim. User-configured server names are replaced with `"custom"` unless `OTEL_LOG_TOOL_DETAILS=1` is set. Absent when the request consumed no MCP tool result. Before v2.1.222, Claude Code set this attribute on every request after an MCP tool call, not only on requests that consumed a tool result, so dashboards that aggregate it show a step down after you upgrade. * `mcp_tool.name`: MCP tool whose result this request consumed, with the same redaction and version behavior as `mcp_server.name`. Absent when the request consumed no MCP tool result. #### @@ -990,8 +990,8 @@ * `marketplace.name`: marketplace the plugin was installed from, when known. Redacted to `"third-party"` under the same condition as `plugin.name` * `plugin.version`: version from the plugin manifest. Included only when the name is not redacted and the manifest declares a version * `plugin.scope`: provenance category for the plugin: `"official"`, `"community"`, `"org"`, `"user-local"`, or `"default-bundle"` - * `enabled_via`: how the plugin came to be enabled: `"default-enable"`, `"org-policy"`, `"admin-install"`, `"seed-mount"`, or `"user-install"`. The `"admin-install"` value means the plugin is set to required or auto-install for your organization in [**Organization settings > Plugins**](<https://claude.ai/admin-settings/plugins>). Before v2.1.246, Claude Code reported these plugins as `"user-install"` or `"seed-mount"` - * `plugin_id_hash`: deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count the distinct third-party plugins loaded across your fleet without recording their names. For [plugins synced from claude.ai](</docs/en/plugins-reference#synced-plugins>), Claude Code hashes the plugin name with the marketplace name that claude.ai reports for the plugin, or with `synced` otherwise. Before v2.1.246, Claude Code didn’t use the marketplace name claude.ai reports in the hash + * `enabled_via`: how the plugin came to be enabled: `"default-enable"`, `"org-policy"`, `"admin-install"`, `"seed-mount"`, or `"user-install"`. The `"admin-install"` value means the plugin is set to required or auto-install for your organization in [**Organization settings > Plugins & skills**](<https://claude.ai/admin-settings/skills?tab=inventory>). Before v2.1.246, Claude Code reported these plugins as `"user-install"` or `"seed-mount"` + * `plugin_id_hash`: deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count the distinct third-party plugins loaded across your fleet without recording their names. For [plugins synced from claude.ai](</docs/en/plugins/loading#synced-plugins>), Claude Code hashes the plugin name with the marketplace name that claude.ai reports for the plugin, or with `synced` otherwise. Before v2.1.246, Claude Code didn’t use the marketplace name claude.ai reports in the hash * `has_hooks`: whether the plugin contributes hooks * `has_mcp`: whether the plugin contributes MCP servers * `host_owned_mcp`: `true` when the SDK host manages this plugin’s MCP connections and Claude Code skipped reading the plugin’s MCP server configuration, `false` otherwise. Requires Claude Code v2.1.172 or later @@ -1239,7 +1239,7 @@ * Set it in the `env` block of managed settings, user settings, or `--settings`, or in the environment you launch Claude Code with. A value in project or local settings doesn’t turn it on, because a cloned repository can write them. * Server-managed settings can set it without showing the [security approval dialog](</docs/en/server-managed-settings#security-approval-dialogs>), because the variable only adds your organization’s own redacted policy to an event your organization already receives. -In an interactive session in a folder you haven’t [trusted](</docs/en/permissions#what-runs-before-you-trust-a-folder>), Claude Code doesn’t export the refusal event, because project and local settings could point the export at a different collector before trust. **Event Name** : `claude_code.managed_settings_resolved` **Attributes** : +In an interactive session in a folder you haven’t [trusted](</docs/en/permissions#what-runs-before-you-trust-a-folder>), Claude Code doesn’t export the refusal event. **Event Name** : `claude_code.managed_settings_resolved` **Attributes** : * All standard attributes * `event.name`: `"managed_settings_resolved"`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1113,6 +1113,11 @@ * `num_non_blocking_error`: Count that failed without blocking * `num_cancelled`: Count cancelled before completion * `total_duration_ms`: Wall-clock duration of all matching hooks + * `stdout_chars`: Total characters of stdout across the matching hooks that succeeded. Requires Claude Code v2.1.280 or later + * `additional_context_chars`: Total characters of `additionalContext` returned by the matching hooks. Requires Claude Code v2.1.280 or later + * `system_message_chars`: Total characters of `systemMessage` returned by the matching hooks. Requires Claude Code v2.1.280 or later + * `initial_user_message_chars`: Total characters of `initialUserMessage` returned by the matching hooks. Requires Claude Code v2.1.280 or later + * `num_outputs_persisted`: Number of hook outputs over the [10,000-character cap](</docs/en/hooks#json-output>) that Claude Code saved to a file. Requires Claude Code v2.1.280 or later * `managed_only`: `"true"` when only managed-policy hooks are permitted * `hook_source`: `"policySettings"` or `"merged"` * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. Requires Claude Code v2.1.169 or later
modified
Show diff (143 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -107,6 +107,7 @@ `OTEL_LOG_ASSISTANT_RESPONSES`| Enable logging of assistant response text on `assistant_response` events (default: disabled). When unset, falls back to the value of `OTEL_LOG_USER_PROMPTS`. Requires Claude Code v2.1.193 or later| `1` to enable, `0` to keep redacted `OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, user-authored workflow names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events (default: disabled). For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `mcp_server_name`/`mcp_tool_name` emit on `tool_decision`/`tool_result` even with the flag off. The exception requires Claude Code v2.1.214 or later| `1` to enable `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool content in the `tool.output` span event (default: disabled). Span attributes carry tool content under their own gates. Requires tracing. Content is truncated at the content limit (60 KB by default)| `1` to enable +`OTEL_LOG_MANAGED_SETTINGS`| Add the redacted managed settings, and a SHA-256 digest of the settings before redaction, to managed settings resolved events (default: disabled). A value in project or local settings doesn’t turn it on. Requires Claude Code v2.1.274 or later| `1` to enable `OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). 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| `1` for inline bodies truncated at the content limit (60 KB by default), or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`| Content limit: the maximum length of content-bearing attributes such as model responses, tool content, system prompts, and raw API bodies, truncation marker included, in UTF-16 code units (default: 61440, i.e. 60 KB). The default is sized for backends that cap attribute values at 64 KB; raise it only if your backend accepts larger values, or lower it to cut telemetry volume. When an OpenTelemetry SDK attribute limit, `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` or one of its logrecord and span variants, is set lower, Claude Code truncates at that smaller value so the `[TRUNCATED ...]` marker stays within the SDK limit. Requires Claude Code v2.1.214 or later| `262144` `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` @@ -215,6 +216,7 @@ `workflow.run_id`| Run identifier of the [Workflow](</docs/en/workflows>) tool run that spawned this agent, prefixed `wf_`. Absent for agents not spawned by a workflow| `workflow.name`| Name of the workflow that spawned this agent. User-authored names are replaced with `custom` unless the gate is set| `OTEL_LOG_TOOL_DETAILS` `speed`| `fast` or `normal`| +`effort`| [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `low`, `medium`, `high`, `xhigh`, or `max`. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. Requires Claude Code v2.1.274 or later| `llm_request.context`| `interaction`, `tool`, or `standalone` depending on the parent span| `duration_ms`| Wall-clock duration including retries| `ttft_ms`| Time to first token in milliseconds| @@ -341,8 +343,9 @@ # Example: Multiple headers echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}" -If the helper fails or prints output that doesn’t meet these requirements, Claude Code reports the error in: - +If the helper fails or prints output that doesn’t meet these requirements, exports fail and your telemetry backend receives nothing from the session until the helper works again. Claude Code reports the failure in: + + * A warning notification in interactive sessions, [`otelHeadersHelper failed; telemetry is not being exported`](</docs/en/errors#otelheadershelper-failed>), shown once per session when the helper first fails * `/status` output * The debug log, when running with [`--debug`](</docs/en/cli-reference#cli-flags>) or after running `/debug` in the session * stderr, in non-interactive sessions started with `-p` @@ -583,7 +586,7 @@ * `model`: Model identifier (for example, “claude-sonnet-5”) * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise - * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model doesn’t support effort. + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. * `agent.name`: Subagent type that issued the request. Built-in agent names and agents from official-marketplace plugins appear verbatim. Other user-defined agent names are replaced with `"custom"`. Absent when the request was not issued by a named subagent type. * `skill.name`: Skill active for the request, set by the Skill tool, a `/` command, or inherited by a spawned subagent. Built-in, bundled, user-defined, and official-marketplace plugin skill names appear verbatim. Third-party plugin skill names are replaced with `"third-party"`. Absent when no skill is active. * `plugin.name`: Owning plugin when the active skill or subagent is provided by a plugin. Official-marketplace plugin names appear verbatim. Third-party plugin names are replaced with `"third-party"`. Absent when neither the skill nor the subagent has an owning plugin. @@ -652,12 +655,12 @@ ---|--- `prompt.id`| UUID v4 identifier linking all events produced while processing a single user prompt `event.sequence`| 0-based counter for ordering events, counted per Claude Code process rather than per session -`message.uuid`| UUID of the message as persisted in the session transcript, the `~/.claude/projects/*/*.jsonl` files. Present on `assistant_response`, and on `user_prompt` except for command dispatches, which can produce zero or many messages. On `assistant_response`, this is the response’s final transcript entry, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.214 or later +`message.uuid`| UUID of the message as persisted in the session transcript, the `~/.claude/projects/*/*.jsonl` files. Present on `assistant_response`, on `api_response_body`, and on `user_prompt` except for command dispatches, which can produce zero or many messages. On `assistant_response` and `api_response_body`, this is the response’s final transcript entry, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.214 or later, or v2.1.274 or later on `api_response_body` `client_request_id`| Client-generated UUID sent as the `x-client-request-id` request header. Present on `api_request` and `api_error` on first-party API connections; absent on third-party provider backends and when the request was retried through the non-streaming fallback. Pairs a request with its response and remains available for failures such as timeouts that never produced a server `request_id`. Matches the same attribute on the `llm_request` trace span. Requires Claude Code v2.1.214 or later To trace all activity triggered by a single prompt, filter your events by a specific `prompt.id` value. This returns the user_prompt event, any api_request events, and any tool_result events that occurred while processing that prompt. `event.sequence` starts at 0 each time a Claude Code process starts and counts up for the life of that process. It keeps counting across `/clear`, which assigns a new `session.id`. If you [resume a session without forking](</docs/en/how-claude-code-works#resume-or-fork-sessions>), the session keeps its `session.id` but takes its `event.sequence` values from the process that resumed it, so within one session a later event can carry a lower value than an earlier one, or repeat one. To order a session’s events, sort by `event.timestamp` and use `event.sequence` to order events that share a timestamp. For message-level reconstruction, each event class carries a key that matches a field in the session transcript. The transcript entry format is [internal to Claude Code](</docs/en/sessions#where-transcripts-are-stored>) and changes between versions, so a pipeline that joins on these fields can break on any release; treat the joins as version-specific rather than a stable contract: - * `message.uuid` on `user_prompt` and `assistant_response` + * `message.uuid` on `user_prompt`, `assistant_response`, and `api_response_body` * `request_id` on the API events, persisted as `requestId` on the transcript’s assistant entries * `tool_use_id` on `tool_result` and `tool_decision` events @@ -754,7 +757,7 @@ * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header; see the event correlation attributes table for when it’s present. Requires Claude Code v2.1.214 or later * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name - * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model doesn’t support effort. + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. #### @@ -778,7 +781,7 @@ * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header. Available even when a failure such as a timeout or connection error never produced a server `request_id`; see the event correlation attributes table for when it’s present. Requires Claude Code v2.1.214 or later * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name - * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when the model doesn’t support effort. + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. #### @@ -798,7 +801,7 @@ * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name. See `api_request` for definitions. * `speed`: Either `"fast"` when [Fast mode](</docs/en/fast-mode>) is active, or `"normal"` * `attempt`: Retry attempt number. The first attempt is `1`. - * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when the model doesn’t support effort. + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. * `server_fallback_hop`: `true` when the API’s server-side model fallback already retried this refusal on a different model, so the user did not see this particular refusal. `false` when the request ended in a refusal. A single turn can emit both a `true` hop event and a later `false` final event when the fallback model also refuses. * `has_category`: `true` when the API response carried a `stop_details.category` of `"cyber"`, `"bio"`, `"frontier_llm"`, or `"reasoning_extraction"`. `false` when the response carried no category or a value outside that set. Absent when `server_fallback_hop` is `true`, because hop blocks don’t carry `stop_details`. * `has_explanation`: `true` when the API response carried a `stop_details.explanation`, otherwise `false`. Absent when `server_fallback_hop` is `true`. @@ -1220,6 +1223,53 @@ * `files_past_cutoff`: Files older than the retention period that the sweep failed to delete, for example because of a permission error or a file held open. A value above zero means files outlived the configured retention period; zero isn’t proof that none did, because a failed removal of a whole directory counts toward `error_count` instead * `error_count`: Number of errors the sweep encountered while listing or deleting files +#### + +​ + +Managed settings resolved event + +Logged with the [managed settings](</docs/en/managed-settings>) a session resolved: once at session start, again when either the managed settings or the [policy helper](</docs/en/managed-settings#compute-the-policy-with-a-helper-program>)’s state changes during the session, and when Claude Code refuses to start or ends the session for one of the reasons the `error.type` attribute lists. Use this event to find machines running on an unexpected managed source, machines whose policy helper is failing, and the reason a machine refused to start. Requires Claude Code v2.1.274 or later. By default, the event carries the managed sources and the policy helper’s state but not the settings themselves. To add the redacted `managed_settings.settings` attribute and the `managed_settings.resolved_sha256` digest, set `OTEL_LOG_MANAGED_SETTINGS=1`: + + * Set it in the `env` block of managed settings, user settings, or `--settings`, or in the environment you launch Claude Code with. A value in project or local settings doesn’t turn it on, because a cloned repository can write them. + * Server-managed settings can set it without showing the [security approval dialog](</docs/en/server-managed-settings#security-approval-dialogs>), because the variable only adds your organization’s own redacted policy to an event your organization already receives. + +In an interactive session in a folder you haven’t [trusted](</docs/en/permissions#what-runs-before-you-trust-a-folder>), Claude Code doesn’t export the refusal event, because project and local settings could point the export at a different collector before trust. **Event Name** : `claude_code.managed_settings_resolved` **Attributes** : + + * All standard attributes + * `event.name`: `"managed_settings_resolved"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes + * `managed_settings.trigger`: `"startup"` for the session-start event, `"change"` when the managed settings or the policy helper’s state changed later in the session, or `"refused"` when a managed settings policy stopped the session. Claude Code sends a `change` event only when an attribute differs from the last event it sent, and a changed setting value counts even when `OTEL_LOG_MANAGED_SETTINGS` is off + * `error.type`: why Claude Code stopped the session. Present only on `refused` events: + * `"helper_failed"`: a [policy helper run failed](</docs/en/settings-reference#helper-failures>) + * `"policy_invalid"`: the managed settings contain an error that stops Claude Code from starting, or an admin source failed to load, so Claude Code can’t check organization login enforcement + * `"consent_rejected"`: the user rejected the [security approval dialog](</docs/en/server-managed-settings#security-approval-dialogs>) for server-managed settings + * `"force_refresh_failed"`: the settings fetch that [`forceRemoteSettingsRefresh`](</docs/en/settings-reference#forceremotesettingsrefresh>) requires failed + * `"gateway_rejected"`: a [Claude apps gateway](</docs/en/claude-apps-gateway>) answered the managed settings load with HTTP 403 + * `"version_below_minimum"`: this version of Claude Code is below [`requiredMinimumVersion`](</docs/en/settings-reference#requiredminimumversion>) or above [`requiredMaximumVersion`](</docs/en/settings-reference#requiredmaximumversion>) + * `"_OTHER"`: the Claude apps gateway managed settings load failed for another reason + * `managed_settings.sources`: every managed source that delivers at least one [policy key](</docs/en/managed-settings#how-claude-code-combines-managed-sources>), highest priority first, including sources whose keys don’t take effect under `first-wins`. Values are `"remote"`, `"plist"` or `"hklm"` for the MDM or OS-level policy, `"file"` for managed settings files and drop-ins, `"parent"` when an [embedding host](</docs/en/managed-settings#let-an-embedding-host-add-policy>) supplies settings, and `"hkcu"` for the [Windows HKCU registry value](</docs/en/managed-settings#where-each-mechanism-stores-the-policy>) when Claude Code [reads it](</docs/en/managed-settings#how-claude-code-combines-managed-sources>). A source that carries only control keys, or that Claude Code couldn’t read, isn’t listed. Emitted as an array of strings, empty when no managed source delivers a policy key + * `managed_settings.source_behavior`: the [`managedSourcesBehavior`](</docs/en/settings-reference#managedsourcesbehavior>) value Claude Code read, `"first-wins"` or `"merge"`. `"first-wins"` when no source sets the key + * `managed_settings.helper.state`: state of the policy helper that the selected MDM or file source configures: + * `"ok"`: the helper’s output serves as the managed settings + * `"bad_path"`, `"not_a_file"`, `"exit_nonzero"`, `"timed_out"`, `"oversize"`, `"parse_failed"`, `"envelope_invalid"`, or `"schema_rejected"`: the helper’s last run failed. [Helper failures](</docs/en/settings-reference#helper-failures>) describes the cases + * `"none"`: no helper is configured, or the source that configures it isn’t an MDM policy or managed settings file + * `managed_settings.helper.applied`: `"output"` while the helper’s own output serves as the managed settings, `"none"` when it doesn’t + * `managed_settings.helper.entry`: `"policyHelper"` when Claude Code selected a [`policyHelper`](</docs/en/settings-reference#policyhelper>). Absent when it selected no helper + * `managed_settings.helper.path`: the helper’s configured [`path`](</docs/en/settings-reference#policyhelper-path>). Present whenever Claude Code selected a helper, whether or not `OTEL_LOG_MANAGED_SETTINGS` is set + * `managed_settings.resolved_sha256` (when `OTEL_LOG_MANAGED_SETTINGS=1`): SHA-256 of the resolved managed settings before redaction, serialized as JSON with keys sorted recursively and no whitespace. Machines with the same digest run the same policy. Claude Code sends the digest only with the opt-in because a short policy can be recovered by hashing guesses. Absent when no managed settings resolved, and on `refused` events + * `managed_settings.settings` (when `OTEL_LOG_MANAGED_SETTINGS=1`): the names and shape of the resolved managed settings as a JSON string, with the values redacted. Absent on `refused` events. Claude Code builds it from its settings schema: + * A setting name the schema declares is exported, and a key it doesn’t declare is left out + * Booleans, numbers, and string values the schema restricts to a fixed set of options, such as `permissions.defaultMode`, are exported as-is. `sandbox.network.httpProxyPort` and `sandbox.network.socksProxyPort` are exported as `"[REDACTED]"` + * Every other string, such as `model`, `apiKeyHelper`, every `env` value, every URL, and every command, is exported as `"[REDACTED]"` + * The entry names of maps, such as `env` variable names and plugin IDs, are exported as-is. A setting whose entries the schema doesn’t type, such as `vimInsertModeRemaps`, is exported as a single `"[REDACTED]"`, and `sandbox.ignoreViolations` is exported as a list of its path lists without the command patterns + * A list keeps its length, with each entry redacted by the same rules + * A `permissions.allow`, `permissions.deny`, or `permissions.ask` rule is exported as its tool name with the content redacted, such as `Read([REDACTED])`, when the tool is built into this version of Claude Code or is an `mcp__` reference such as `mcp__jira__create_issue`. Any other rule is exported as `"[REDACTED]"` + * Hooks follow the same rules, so fixed-option and numeric fields such as `type` and `timeout` show, while each command, URL, `matcher`, and `if` condition is exported as `"[REDACTED]"` +For example, managed settings with `apiKeyHelper`, two `env` variables, and a deny rule are exported as `{"apiKeyHelper":"[REDACTED]","env":{"HTTPS_PROXY":"[REDACTED]","CLAUDE_CODE_ENABLE_TELEMETRY":"[REDACTED]"},"permissions":{"deny":["Read([REDACTED])"]}}`. Claude Code cuts the value at 8 KB of UTF-8, and the cut value isn’t valid JSON + * `managed_settings.settings_truncated` (when `managed_settings.settings` is present): `true` when Claude Code cut `managed_settings.settings` at 8 KB, `false` otherwise. Emitted as a boolean, not a string + ## ​ @@ -1349,6 +1399,7 @@ MCP server connect or failure| `mcp_server_connection`| `status`, `server_name`, `is_plugin`, `error_code` Plugin installed and its source| `plugin_installed`| `plugin.name`, `marketplace.name`, `marketplace.is_official` Commands run and files touched| `tool_result` (executed) or `tool_decision` (rejected) with `OTEL_LOG_TOOL_DETAILS=1`| `tool_parameters`; `tool_input` (`tool_result` only) +Which managed settings sources a machine runs on, whether its policy helper is healthy, and why a machine refused to start| `managed_settings_resolved`| `managed_settings.trigger`, `managed_settings.sources`, `managed_settings.source_behavior`, `managed_settings.helper.state`, `error.type`; `managed_settings.settings` and `managed_settings.resolved_sha256` with `OTEL_LOG_MANAGED_SETTINGS=1` Claude Code emits the raw event stream only. Anomaly detection, baselining, correlation across sessions, and alerting are the responsibility of your SIEM or observability backend.
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -106,7 +106,7 @@ `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable `OTEL_LOG_ASSISTANT_RESPONSES`| Enable logging of assistant response text on `assistant_response` events (default: disabled). When unset, falls back to the value of `OTEL_LOG_USER_PROMPTS`. Requires Claude Code v2.1.193 or later| `1` to enable, `0` to keep redacted `OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, user-authored workflow names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events (default: disabled). For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `mcp_server_name`/`mcp_tool_name` emit on `tool_decision`/`tool_result` even with the flag off. The exception requires Claude Code v2.1.214 or later| `1` to enable -`OTEL_LOG_TOOL_CONTENT`| Enable logging of tool input and output content in span events (default: disabled). Requires tracing. Content is truncated at the content limit (60 KB by default)| `1` to enable +`OTEL_LOG_TOOL_CONTENT`| Enable logging of tool content in the `tool.output` span event (default: disabled). Span attributes carry tool content under their own gates. Requires tracing. Content is truncated at the content limit (60 KB by default)| `1` to enable `OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). 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| `1` for inline bodies truncated at the content limit (60 KB by default), or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`| Content limit: the maximum length of content-bearing attributes such as model responses, tool content, system prompts, and raw API bodies, truncation marker included, in UTF-16 code units (default: 61440, i.e. 60 KB). The default is sized for backends that cap attribute values at 64 KB; raise it only if your backend accepts larger values, or lower it to cut telemetry volume. When an OpenTelemetry SDK attribute limit, `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` or one of its logrecord and span variants, is set lower, Claude Code truncates at that smaller value so the `[TRUNCATED ...]` marker stays within the SDK limit. Requires Claude Code v2.1.214 or later| `262144` `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` @@ -256,7 +256,23 @@ `skill_name`| Skill name for the Skill tool| `OTEL_LOG_TOOL_DETAILS` `subagent_type`| Subagent type for the Agent tool or legacy Task tool| `OTEL_LOG_TOOL_DETAILS` -When `OTEL_LOG_TOOL_CONTENT=1`, this span also records a `tool.output` span event whose attributes contain the tool’s input and output bodies, truncated at the content limit (60 KB by default) per attribute. **`claude_code.tool.blocked_on_user`** +**`tool.output` span event on `claude_code.tool`** If you set `OTEL_LOG_TOOL_CONTENT=1`, Read and Bash calls can record a `tool.output` span event on the `claude_code.tool` span. Edit and Write calls record one only when you also set `OTEL_LOG_TOOL_DETAILS=1`. That variable isn’t scoped to those two tools, so check its row in the configuration table for the arguments it adds elsewhere. Claude Code writes this event from a tool call’s successful return, so a call that raises an error records nothing, whatever the tool. Among the calls that do return, it records no `tool.output` event for: + + * A call to any tool other than Read, Edit, Write, and Bash, including MCP tools and WebFetch + * A Read that returns anything other than file text, such as an image, a PDF, or a re-read of a file whose contents haven’t changed + * An Edit or Write call, unless you also set `OTEL_LOG_TOOL_DETAILS=1` + +The event carries these attributes, each truncated at the content limit (60 KB by default). `Gated by` names the variable an attribute needs on top of `OTEL_LOG_TOOL_CONTENT=1`, and for Edit and Write that variable gates the event itself rather than the attribute. + +Attribute| Description| Gated by +---|---|--- +`content`| Text the Read tool returned, or the text a Write call was asked to write| `OTEL_LOG_TOOL_DETAILS` for the Write tool +`output`| Combined output of a Bash command, with stderr interleaved into stdout| +`diff`| Structured patch the Edit tool applied| `OTEL_LOG_TOOL_DETAILS` +`file_path`| Target file path for the Read, Edit, and Write tools, repeating the span attribute of the same name| `OTEL_LOG_TOOL_DETAILS` +`bash_command`| Command string for the Bash tool| `OTEL_LOG_TOOL_DETAILS` + +The parent span’s `tool_name` attribute tells you which tool an event came from. An attribute cut at the content limit is accompanied by `<attribute>_truncated` and `<attribute>_original_length`. **`claude_code.tool.blocked_on_user`** Attribute| Description| Gated by ---|---|--- @@ -289,7 +305,7 @@ `num_non_blocking_error`| Count of hooks that failed without blocking| `num_cancelled`| Count of hooks cancelled before completion| -Additional content-bearing attributes such as `new_context`, `system_prompt_preview`, `user_system_prompt`, `tool_input`, and `response.model_output` are emitted only when detailed beta tracing is active. They are not part of the stable span schema.`user_system_prompt` additionally requires `OTEL_LOG_USER_PROMPTS=1`. It carries only the system prompt text you provide via the `systemPrompt` SDK option or `--system-prompt` and `--append-system-prompt` flags, truncated at the content limit (60 KB by default), and is emitted once per session rather than per request. +Additional content-bearing attributes such as `new_context`, `system_prompt_preview`, `user_system_prompt`, `tool_input`, and `response.model_output` are emitted only when detailed beta tracing is active. They are not part of the stable span schema.The gate on `new_context` depends on which span carries it, and each copy is truncated at the content limit (60 KB by default). On the `claude_code.tool` span it carries that tool call’s result, whatever the tool, and requires `OTEL_LOG_TOOL_CONTENT=1`. On the `claude_code.interaction` span it carries the user prompt, and on the `claude_code.llm_request` span the new user messages and tool results of that request. Both of those require `OTEL_LOG_USER_PROMPTS=1`.`user_system_prompt` additionally requires `OTEL_LOG_USER_PROMPTS=1`. It carries only the system prompt text you provide via the `systemPrompt` SDK option or `--system-prompt` and `--append-system-prompt` flags, truncated at the content limit (60 KB by default), and is emitted once per session rather than per request. ### @@ -807,6 +823,7 @@ * `body_truncated`: `"true"` when inline truncation occurred. Absent in file mode and when no truncation occurred. * `model`: Model identifier from the request parameters * `query_source`: Subsystem that issued the request (for example, `"compact"`) + * `request_body_id`: UUID that identifies this attempt’s request body. The `api_response_body` event for the attempt that succeeds carries the same value, so you can pair a response with the exact request that produced it. Requires Claude Code v2.1.274 or later #### @@ -814,7 +831,7 @@ API response body event -Logged for each successful API response when `OTEL_LOG_RAW_API_BODIES` is set. **Event Name** : `claude_code.api_response_body` **Attributes** : +Logged for each successful API response when `OTEL_LOG_RAW_API_BODIES` is set. In file mode (`OTEL_LOG_RAW_API_BODIES=file:<dir>`), Claude Code also appends one JSON line to `<dir>/index.jsonl` for each successful response, with the fields `timestamp`, `session_id`, `query_source`, `model`, `request_id`, `message_id`, `message_uuid`, `request_file`, and `response_file`. Read it to find the request and response files behind a given transcript message without querying your telemetry backend. The index file requires Claude Code v2.1.274 or later. **Event Name** : `claude_code.api_response_body` **Attributes** : * All standard attributes * `event.name`: `"api_response_body"` @@ -827,6 +844,9 @@ * `model`: Model identifier * `query_source`: Subsystem that issued the request * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. + * `request_body_id`: The `request_body_id` of the `api_request_body` event that this response answers. Requires Claude Code v2.1.274 or later + * `message.id`: Message ID the API assigned to the response, the `id` field of the response body. Requires Claude Code v2.1.274 or later + * `message.uuid`: UUID of the response’s final transcript entry. Together with `request_body_id`, it links a transcript message to the request and response bodies behind it. Requires Claude Code v2.1.274 or later #### @@ -1429,17 +1449,17 @@ * OpenTelemetry export to your backend is opt-in and requires explicit configuration. For Anthropic’s separate operational telemetry and how to disable it, see [Data usage](</docs/en/data-usage#telemetry-services>) * Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below * When authenticated via OAuth, `user.email` is included in telemetry attributes, sent only to the OTel endpoint you configure, never to Anthropic. If this is a concern for your organization, work with your telemetry backend to filter or redact this field - * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` + * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1`. Under detailed beta tracing this variable reaches further than prompt text: it also gates the `new_context` span attribute, which carries tool results on the `claude_code.llm_request` span * Assistant response text is not collected by default. Only response length is recorded. To include response text, set `OTEL_LOG_ASSISTANT_RESPONSES=1`. Like all OpenTelemetry data from Claude Code, the response text is sent only to the OTel endpoint you configure, never to Anthropic. When this variable is unset, `OTEL_LOG_USER_PROMPTS` is used as a fallback, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` if you want prompt content without response content * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `tool_decision` and `tool_result` carry the `mcp_server_name`/`mcp_tool_name` pair, host-authored names rather than argument content, even with the flag off. The exception requires Claude Code v2.1.214 or later. This data is sent only to the OTEL endpoint you configure, never to Anthropic. Arguments may still contain sensitive values, so configure your telemetry backend to filter or redact these attributes as needed. When enabled: * `tool_result` and `tool_decision` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names. Fields such as `full_command` are emitted untruncated * `tool_result` events additionally include a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters * `user_prompt` events include the verbatim `command_name` for custom, plugin, and MCP commands * Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`, with the same truncation as `tool_input` - * Tool input and output content is not logged in trace spans by default. To include it, set `OTEL_LOG_TOOL_CONTENT=1`. When enabled, span events include full tool input and output content truncated at the content limit (60 KB by default) per attribute. This can include raw file contents from Read tool results and Bash command output. Configure your telemetry backend to filter or redact these attributes as needed + * Tool content is not logged in trace spans by default. 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 and Bash command output, truncated at the content limit (60 KB by default) per attribute. Tool content also reaches spans through `new_context`, whose gate differs per span. Configure your telemetry backend to filter or redact these attributes as needed * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES` in your shell, user settings, or managed settings. It’s ignored in [project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). The bodies contain the full conversation history, including the system prompt, every prior user and assistant turn, and tool results, so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude Code always redacts Claude’s extended-thinking content from these bodies, regardless of other settings. The value you set determines how Claude Code delivers the bodies: * With `=1`, Claude Code emits `api_request_body` and `api_response_body` log events for each API call. The events’ `body` attribute carries the JSON-serialized payload, truncated at the content limit (60 KB by default) - * With `=file:<dir>`, Claude Code writes untruncated bodies to `.request.json` and `.response.json` files under that directory, and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream + * With `=file:<dir>`, Claude Code writes untruncated bodies to `.request.json` and `.response.json` files under that directory, and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. For each successful response, Claude Code also appends one line to `index.jsonl` in that directory, linking the response file to the request file that produced it and to the transcript message it became. Each line holds no message content, and the API response body event section lists its fields. The index file requires Claude Code v2.1.274 or later ##
modified
Show diff (258 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -197,7 +197,7 @@ ---|---|--- `user_prompt`| Prompt text. Value is `<REDACTED>` unless the gate is set| `OTEL_LOG_USER_PROMPTS` `user_prompt_length`| Prompt length in characters| -`interaction.sequence`| 1-based counter of interactions in this session| +`interaction.sequence`| 1-based counter of interactions, counted per Claude Code process rather than per session, as described for `event.sequence`| `parent.source`| How the span got its trace parent: `env` when it parented under an inbound `TRACEPARENT`, `none` when it started its own trace. Requires Claude Code v2.1.268 or later| `interaction.duration_ms`| Wall-clock duration of the turn| @@ -635,10 +635,11 @@ Attribute| Description ---|--- `prompt.id`| UUID v4 identifier linking all events produced while processing a single user prompt +`event.sequence`| 0-based counter for ordering events, counted per Claude Code process rather than per session `message.uuid`| UUID of the message as persisted in the session transcript, the `~/.claude/projects/*/*.jsonl` files. Present on `assistant_response`, and on `user_prompt` except for command dispatches, which can produce zero or many messages. On `assistant_response`, this is the response’s final transcript entry, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.214 or later `client_request_id`| Client-generated UUID sent as the `x-client-request-id` request header. Present on `api_request` and `api_error` on first-party API connections; absent on third-party provider backends and when the request was retried through the non-streaming fallback. Pairs a request with its response and remains available for failures such as timeouts that never produced a server `request_id`. Matches the same attribute on the `llm_request` trace span. Requires Claude Code v2.1.214 or later -To trace all activity triggered by a single prompt, filter your events by a specific `prompt.id` value. This returns the user_prompt event, any api_request events, and any tool_result events that occurred while processing that prompt. For message-level reconstruction, each event class carries a key that matches a field in the session transcript. The transcript entry format is [internal to Claude Code](</docs/en/sessions#where-transcripts-are-stored>) and changes between versions, so a pipeline that joins on these fields can break on any release; treat the joins as version-specific rather than a stable contract: +To trace all activity triggered by a single prompt, filter your events by a specific `prompt.id` value. This returns the user_prompt event, any api_request events, and any tool_result events that occurred while processing that prompt. `event.sequence` starts at 0 each time a Claude Code process starts and counts up for the life of that process. It keeps counting across `/clear`, which assigns a new `session.id`. If you [resume a session without forking](</docs/en/how-claude-code-works#resume-or-fork-sessions>), the session keeps its `session.id` but takes its `event.sequence` values from the process that resumed it, so within one session a later event can carry a lower value than an earlier one, or repeat one. To order a session’s events, sort by `event.timestamp` and use `event.sequence` to order events that share a timestamp. For message-level reconstruction, each event class carries a key that matches a field in the session transcript. The transcript entry format is [internal to Claude Code](</docs/en/sessions#where-transcripts-are-stored>) and changes between versions, so a pipeline that joins on these fields can break on any release; treat the joins as version-specific rather than a stable contract: * `message.uuid` on `user_prompt` and `assistant_response` * `request_id` on the API events, persisted as `requestId` on the transcript’s assistant entries @@ -655,7 +656,7 @@ * All standard attributes * `event.name`: `"user_prompt"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `prompt_length`: Length of the prompt * `prompt`: Prompt content. Redacted by default. Set `OTEL_LOG_USER_PROMPTS=1` to include it * `message.uuid`: UUID of the resulting user message, matching the persisted transcript entry. Absent on command dispatches, which can produce zero or many messages. Requires Claude Code v2.1.214 or later @@ -673,7 +674,7 @@ * All standard attributes * `event.name`: `"assistant_response"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `response_length`: Length of the response text in characters * `response`: Response text, truncated at the content limit (60 KB by default). Redacted to `<REDACTED>` by default. Set `OTEL_LOG_ASSISTANT_RESPONSES=1` to include it. When `OTEL_LOG_ASSISTANT_RESPONSES` is unset, `OTEL_LOG_USER_PROMPTS` controls it instead, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` to keep responses redacted while prompt logging is on * `model`: Model identifier (for example, “claude-sonnet-5”) @@ -692,7 +693,7 @@ * All standard attributes * `event.name`: `"tool_result"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `tool_name`: Name of the tool * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. * `success`: `"true"` or `"false"` @@ -724,7 +725,7 @@ * All standard attributes * `event.name`: `"api_request"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `model`: Model used (for example, “claude-sonnet-5”) * `cost_usd`: Estimated cost in USD * `cost_usd_micros`: Estimated cost in millionths of a US dollar, emitted as an integer @@ -751,7 +752,7 @@ * All standard attributes * `event.name`: `"api_error"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `model`: Model used (for example, “claude-sonnet-5”) * `error`: Error message * `status_code`: HTTP status code as a number. Absent for non-HTTP errors such as connection failures. @@ -775,7 +776,7 @@ * All standard attributes * `event.name`: `"api_refusal"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `model`: Model identifier from the request * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name. See `api_request` for definitions. @@ -799,7 +800,7 @@ * All standard attributes * `event.name`: `"api_request_body"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `body`: JSON-serialized Messages API request parameters, such as the system prompt, messages, and tools, truncated at the content limit (60 KB by default). Extended-thinking content in prior assistant turns is redacted. Emitted only in inline mode (`OTEL_LOG_RAW_API_BODIES=1`). * `body_ref`: Absolute path to a `<dir>/<uuid>.request.json` file containing the untruncated body. Emitted only in file mode (`OTEL_LOG_RAW_API_BODIES=file:<dir>`). * `body_length`: Untruncated body length. UTF-8 bytes when `OTEL_LOG_RAW_API_BODIES=file:<dir>`, or UTF-16 code units when `=1` @@ -818,7 +819,7 @@ * All standard attributes * `event.name`: `"api_response_body"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `body`: JSON-serialized Messages API response, including the id, content blocks, usage, and stop reason, truncated at the content limit (60 KB by default). Extended-thinking content is redacted. Emitted only in inline mode (`OTEL_LOG_RAW_API_BODIES=1`). * `body_ref`: Absolute path to a `<dir>/<request_id>.response.json` file containing the untruncated body. Emitted only in file mode (`OTEL_LOG_RAW_API_BODIES=file:<dir>`). * `body_length`: Untruncated body length. UTF-8 bytes when `OTEL_LOG_RAW_API_BODIES=file:<dir>`, or UTF-16 code units when `=1` @@ -838,7 +839,7 @@ * All standard attributes * `event.name`: `"tool_decision"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `tool_name`: Name of the tool (for example, “Read”, “Edit”, “Write”, “NotebookEdit”) * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. * `decision`: Either `"accept"` or `"reject"` @@ -871,7 +872,7 @@ * All standard attributes * `event.name`: `"permission_mode_changed"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `from_mode`: The previous permission mode, for example `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, or `"bypassPermissions"` * `to_mode`: The new permission mode * `trigger`: What caused the change. One of `"shift_tab"`, `"exit_plan_mode"`, `"auto_gate_denied"`, or `"auto_opt_in"`. Absent when the transition originates from the SDK or bridge @@ -887,7 +888,7 @@ * All standard attributes * `event.name`: `"auth"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `action`: `"login"` or `"logout"` * `success`: `"true"` or `"false"` * `auth_method`: Authentication method, such as `"oauth"` @@ -905,7 +906,7 @@ * All standard attributes * `event.name`: `"mcp_server_connection"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `status`: `"connected"`, `"failed"`, or `"disconnected"` * `transport_type`: Server transport, such as `"stdio"`, `"sse"`, or `"http"` * `server_scope`: Scope the server is configured at, such as `"user"`, `"project"`, or `"local"` @@ -928,7 +929,7 @@ * All standard attributes * `event.name`: `"internal_error"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `error_name`: Error class name, such as `"TypeError"` or `"SyntaxError"` * `error_code`: Node.js errno code such as `"ENOENT"` when present on the error @@ -943,7 +944,7 @@ * All standard attributes * `event.name`: `"plugin_installed"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `marketplace.is_official`: `"true"` if the marketplace is an official Anthropic marketplace, `"false"` otherwise * `install.trigger`: `"cli"` or `"ui"` * `plugin.name`: Name of the installed plugin. For third-party marketplaces this is included only when `OTEL_LOG_TOOL_DETAILS=1` @@ -961,7 +962,7 @@ * All standard attributes * `event.name`: `"plugin_loaded"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `plugin.name`: name of the plugin. For plugins outside the official marketplace and built-in bundle the value is `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` * `marketplace.name`: marketplace the plugin was installed from, when known. Redacted to `"third-party"` under the same condition as `plugin.name` * `plugin.version`: version from the plugin manifest. Included only when the name is not redacted and the manifest declares a version @@ -987,7 +988,7 @@ * All standard attributes * `event.name`: `"skill_activated"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `skill.name`: Name of the skill. For user-defined and third-party plugin skills the value is the placeholder `"custom_skill"` unless `OTEL_LOG_TOOL_DETAILS=1` * `invocation_trigger`: How the skill was triggered (`"user-slash"`, `"claude-proactive"`, or `"nested-skill"`) * `skill.source`: Where the skill was loaded from (for example, `"bundled"`, `"userSettings"`, `"projectSettings"`, `"plugin"`) @@ -1006,7 +1007,7 @@ * All standard attributes * `event.name`: `"at_mention"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `mention_type`: Type of mention (`"file"`, `"directory"`, `"agent"`, `"mcp_resource"`, `"peer"`). The `"peer"` value means you mentioned [one of your other Claude Code sessions](</docs/en/cross-session-messaging>). Requires Claude Code v2.1.232 or later * `success`: Whether the mention resolved successfully (`"true"` or `"false"`) @@ -1021,7 +1022,7 @@ * All standard attributes * `event.name`: `"api_retries_exhausted"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `model`: Model used * `error`: Final error message * `status_code`: HTTP status code as a number. Absent for non-HTTP errors. @@ -1040,7 +1041,7 @@ * All standard attributes * `event.name`: `"hook_registered"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `hook_event`: hook event type, such as `"PreToolUse"` or `"PostToolUse"` * `hook_type`: hook implementation type: `"command"`, `"prompt"`, `"mcp_tool"`, `"http"`, or `"agent"` * `hook_source`: where the hook is defined: `"userSettings"`, `"projectSettings"`, `"localSettings"`, `"flagSettings"`, `"policySettings"`, or `"pluginHook"` @@ -1060,7 +1061,7 @@ * All standard attributes * `event.name`: `"hook_execution_start"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `hook_event`: Hook event type, such as `"PreToolUse"` or `"PostToolUse"` * `hook_name`: Full hook name including matcher, such as `"PreToolUse:Write"` * `num_hooks`: Number of matching hook commands @@ -1080,7 +1081,7 @@ * All standard attributes * `event.name`: `"hook_execution_complete"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `hook_event`: Hook event type * `hook_name`: Full hook name including matcher * `num_hooks`: Number of matching hook commands @@ -1105,7 +1106,7 @@ * All standard attributes * `event.name`: `"hook_plugin_metrics"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `plugin_id`: plugin identifier in `<name>@<marketplace>` form * `hook_event`: hook event type that emitted the metrics * Up to 20 plugin-emitted metric keys. Names match `^[a-z][a-z0-9_]{0,39}$`. Values are boolean or number. @@ -1121,7 +1122,7 @@ * All standard attributes * `event.name`: `"compaction"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `trigger`: `"auto"` or `"manual"` * `success`: `"true"` or `"false"` * `duration_ms`: Compaction duration @@ -1141,7 +1142,7 @@ * All standard attributes * `event.name`: `"subagent_completed"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `agent_type`: The subagent type. Built-in agent names and agents from official-marketplace plugins appear verbatim; other agent names are replaced with `"custom"` unless `OTEL_LOG_TOOL_DETAILS=1` is set * `agent.source`: Where the agent definition came from: `built-in`, `plugin`, or the settings source that defined a custom agent, such as `userSettings` or `projectSettings` * `is_built_in`: Whether the subagent is a built-in agent type @@ -1165,7 +1166,7 @@ * All standard attributes * `event.name`: `"feedback_survey"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `event_type`: Survey lifecycle event, for example `"appeared"`, `"responded"`, or `"transcript_prompt_appeared"` * `appearance_id`: Unique ID linking the events emitted for one survey instance * `survey_type`: Which survey produced the event. `"session"` is the “How is Claude doing?” rating prompt @@ -1183,7 +1184,7 @@ * All standard attributes * `event.name`: `"retention_sweep"` * `event.timestamp`: ISO 8601 timestamp - * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event.sequence`: per-process counter for ordering events, described under Event correlation attributes * `result`: `"complete"` when the sweep ran, `"skipped"` when Claude Code paused it * `period_days`: The `cleanupPeriodDays` value from merged settings, in days, or `30` when no source sets it. On skipped events, the value the sweep would have used, computed from the settings sources Claude Code could read * `used_default`: `"true"` when no readable settings source sets `cleanupPeriodDays`, `"false"` otherwise. On complete events, `"true"` means the 30-day default applied
modified
Show diff (115 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -144,6 +144,7 @@ `OTEL_METRICS_INCLUDE_ACCOUNT_UUID`| Include user.account_uuid and user.account_id attributes in metrics| `true`| `false` `OTEL_METRICS_INCLUDE_ENTRYPOINT`| Include app.entrypoint attribute in metrics| `false`| `true` `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES`| Include keys from `OTEL_RESOURCE_ATTRIBUTES` as attributes on metric datapoints| `true`| `false` +`OTEL_METRICS_INCLUDE_REPOSITORY`| Include `vcs.*` repository identity attributes on metrics and events. Requires Claude Code v2.1.269 or later| `false`| `true` Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. @@ -197,6 +198,7 @@ `user_prompt`| Prompt text. Value is `<REDACTED>` unless the gate is set| `OTEL_LOG_USER_PROMPTS` `user_prompt_length`| Prompt length in characters| `interaction.sequence`| 1-based counter of interactions in this session| +`parent.source`| How the span got its trace parent: `env` when it parented under an inbound `TRACEPARENT`, `none` when it started its own trace. Requires Claude Code v2.1.268 or later| `interaction.duration_ms`| Wall-clock duration of the turn| **`claude_code.llm_request`** @@ -206,7 +208,8 @@ `model`| Model identifier| `gen_ai.system`| Always `anthropic`. OpenTelemetry GenAI semantic convention| `gen_ai.request.model`| Same value as `model`. OpenTelemetry GenAI semantic convention| -`query_source`| Subsystem that issued the request, such as `repl_main_thread` or a subagent name| +`query_source`| Subsystem that issued the request, such as `repl_main_thread` or a subagent name| `ENABLE_BETA_TRACING_DETAILED` +`query_source_safe`| Bounded form of `query_source`, emitted whether or not detailed beta tracing is active, with values such as `repl_main_thread` or `agent.builtin.general-purpose`. `:` becomes `.` and user-named agents appear as `agent.custom`. Requires Claude Code v2.1.268 or later| `agent_id`| Identifier of the subagent or teammate that issued the request. Absent on the main session| `parent_agent_id`| Identifier of the agent that spawned this one. Absent for the main session and for agents spawned directly from it| `workflow.run_id`| Run identifier of the [Workflow](</docs/en/workflows>) tool run that spawned this agent, prefixed `wf_`. Absent for agents not spawned by a workflow| @@ -215,6 +218,7 @@ `llm_request.context`| `interaction`, `tool`, or `standalone` depending on the parent span| `duration_ms`| Wall-clock duration including retries| `ttft_ms`| Time to first token in milliseconds| +`first_content_ms`| Time from request start to the first content block of the successful attempt, in milliseconds. Absent on requests that fell back to the non-streaming path. Requires Claude Code v2.1.268 or later| `input_tokens`| Input token count from the API usage block| `output_tokens`| Output token count| `cache_read_tokens`| Tokens read from prompt cache| @@ -226,6 +230,7 @@ `success`| `true` or `false`| `status_code`| HTTP status code when the request failed| `error`| Error message when the request failed| +`error_class`| Short error class token when the request failed, such as `api_timeout` or `server_overload`. Requires Claude Code v2.1.268 or later| `response.has_tool_call`| `true` when the response contained tool-use blocks| `stop_reason`| API response `stop_reason`, such as `end_turn`, `tool_use`, `max_tokens`, `stop_sequence`, `pause_turn`, or `refusal`| `gen_ai.response.finish_reasons`| Same value as `stop_reason`, wrapped in a string array. OpenTelemetry GenAI semantic convention| @@ -235,6 +240,9 @@ Attribute| Description| Gated by ---|---|--- `tool_name`| Tool name| +`tool_name_safe`| Form of `tool_name` that carries no user-chosen names. Built-in tool names pass verbatim. MCP tool names appear as `mcp_other`, except tool names matching a few fixed shapes, such as `playwright` tools named `browser_*`, which pass verbatim. Requires Claude Code v2.1.268 or later| +`bash_command_class`| For the Bash tool: category of the command’s first program from a fixed list, such as `vcs` or `package_manager`. `other` for a program outside the list, `unparsed` when the line can’t be parsed. Requires Claude Code v2.1.268 or later| +`bash_argv0`| For the Bash tool: the command’s first program when it’s on the same fixed list, such as `git` or `npm`. `other` for any program outside the list. Requires Claude Code v2.1.268 or later| `duration_ms`| Wall-clock duration including permission wait and execution| `result_tokens`| Approximate token size of the tool result| `agent_id`| Identifier of the subagent or teammate that ran the tool. Absent on the main session| @@ -265,6 +273,7 @@ `gen_ai.tool.call.id`| Same value as `tool_use_id`. OpenTelemetry GenAI semantic convention| `success`| `true` or `false`| `error`| Error category string when execution failed, such as `Error:ENOENT` or `ShellError`. Contains the full error message instead when the gate is set| `OTEL_LOG_TOOL_DETAILS` +`error_class`| The error category in identifier form, with characters outside letters, digits, and underscores replaced by `_`, such as `Error_ENOENT` or `ShellError`. Carries the category even when `error` carries the full message. Requires Claude Code v2.1.268 or later| **`claude_code.hook`** This span appears only when detailed beta tracing is active, which requires `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>). Set the pair in your shell, user settings, or managed settings; both variables are ignored in [project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` alone doesn’t produce it. In interactive CLI sessions, detailed beta tracing also requires your organization to be allowlisted for the feature. Agent SDK and non-interactive `-p` sessions don’t require allowlisting. @@ -348,7 +357,7 @@ * Create team-specific dashboards * Set up alerts for specific teams -Claude Code attaches these values as attributes on every metric datapoint and event record, in addition to sending them in the OTLP resource block. Because most metrics backends expose datapoint attributes as queryable labels, you can group and filter metrics by your custom keys directly. Custom keys never override the standard attributes such as `user.id` or `session.id`: when a key collides, Claude Code keeps the built-in value. Each custom key becomes a label on every metric series, so high-cardinality values increase storage cost in your metrics backend. To send custom attributes in the resource block only and omit them from datapoint labels, set `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES=false`. See Metrics cardinality control. +Claude Code attaches these values as attributes on every metric datapoint and event record, in addition to sending them in the OTLP resource block. Because most metrics backends expose datapoint attributes as queryable labels, you can group and filter metrics by your custom keys directly. Except for the `vcs.*` repository attributes, custom keys never override the standard attributes such as `user.id` or `session.id`: when a key collides, Claude Code keeps the built-in value. Each custom key becomes a label on every metric series, so high-cardinality values increase storage cost in your metrics backend. To send custom attributes in the resource block only and omit them from datapoint labels, set `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES=false`. See Metrics cardinality control. The `OTEL_RESOURCE_ATTRIBUTES` environment variable uses comma-separated key=value pairs with strict formatting requirements: @@ -448,6 +457,7 @@ `user.email`| User email address, from your sign-in or, in a [cloud session](</docs/en/claude-code-on-the-web>), from the session’s own credentials| Always included when available `terminal.type`| Terminal type, such as `iTerm.app`, `vscode`, `cursor`, or `tmux`| Always included when detected Keys from `OTEL_RESOURCE_ATTRIBUTES`| Custom attributes you set, such as `department` or `team.id`. See Multi-team organization support| `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES` (default: true) +`vcs.repository.url.full`, `vcs.owner.name`, `vcs.repository.name`, `vcs.provider.name`| The session repository’s identity, derived from its `origin` remote. See Repository attributes| `OTEL_METRICS_INCLUDE_REPOSITORY` (default: false). Requires Claude Code v2.1.269 or later When Claude Code is signed in to a [Claude apps gateway](</docs/en/claude-apps-gateway>), the CLI stamps exports with the authenticated identity from the gateway session: `user.id` is the IdP subject rather than an anonymous installation identifier, `user.email` is the signed-in email, and `user.groups` carries IdP group membership as a comma-separated string. Each export also carries `identity.source: gateway-oidc`. The gateway identity is applied last, so `user.*` and `identity.*` keys set through `OTEL_RESOURCE_ATTRIBUTES` are ignored on gateway sessions. Events additionally include the following attributes. These are never attached to metrics because they would cause unbounded cardinality: @@ -455,6 +465,23 @@ * `workspace.host_paths`: host workspace directories selected in the desktop app, as a string array * `workflow.run_id`: run identifier, prefixed `wf_`, on the API and tool events emitted by agents that belong to a [Workflow](</docs/en/workflows>) tool run. Filtering events by one `workflow.run_id` reconstructs that run’s API requests and tool results. The identifier covers the agents the workflow script spawns and any agents those spawn in turn, such as skill invocations. It matches the run identifier reported in the Workflow tool result. Absent on all other events. Requires Claude Code v2.1.202 or later * `workflow.name`: name of the workflow, its script’s `meta.name`, emitted alongside `workflow.run_id`. Built-in workflow names appear verbatim when the run executes the unmodified built-in script. User-authored names, including edited copies of built-in scripts, are replaced with `custom` unless `OTEL_LOG_TOOL_DETAILS=1` is set. Requires Claude Code v2.1.202 or later + +#### + +​ + +Repository attributes + +Set `OTEL_METRICS_INCLUDE_REPOSITORY=true` to tag metrics and events with the identity of the session’s repository, so a shared collector can attribute usage per repository. Requires Claude Code v2.1.269 or later. Claude Code derives these attributes once per session from the repository’s `origin` remote. The HTTPS and SSH remotes of one repository produce identical values: + +Attribute| Value +---|--- +`vcs.repository.url.full`| The repository’s browser URL without `.git`, such as `https://github.com/example-org/example-repo` +`vcs.owner.name`| The owner or group path, such as `example-org`; omitted when the remote path has a single segment +`vcs.repository.name`| The bare repository name, such as `example-repo` +`vcs.provider.name`| `github`, `gitlab`, `bitbucket`, or `gitea` when Claude Code recognizes the remote’s host or URL shape as one of those providers; omitted otherwise + +Values are lowercased, and credentials, query strings, and fragments from the remote URL never appear in them. The attributes are omitted when the session has no `origin` remote, when the remote isn’t URL-shaped, or when the only enclosing repository is your home directory. A `vcs.*` key you declare in `OTEL_RESOURCE_ATTRIBUTES` replaces the derived value for that key. If you declare `vcs.repository.url.full`, Claude Code never reads the remote and reports only the keys you declare. The attributes flow only to your own exporters; Anthropic’s telemetry drops every `vcs.*` key. ### @@ -677,8 +704,10 @@ * `tool_input_size_bytes`: Size of the JSON-serialized tool input in bytes * `tool_result_size_bytes`: Size of the tool result in bytes * `mcp_server_scope`: MCP server scope identifier (for MCP tools) + * `vcs.ref.head.revision`, `vcs.ref.head.name`, `vcs.ref.head.type` (when `OTEL_LOG_TOOL_DETAILS=1`): the commit identity of a successful `git commit` run by the Bash or PowerShell tool. `vcs.ref.head.revision` is the commit SHA, `vcs.ref.head.name` is the branch it was committed on, and `vcs.ref.head.type` is `branch`. The name and type are omitted when the commit was made on a detached HEAD. Requires Claude Code v2.1.269 or later * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, the `mcp_server_name`/`mcp_tool_name` pair is included even with the flag off, the same host-authored exception as the Tool decision event, requiring Claude Code v2.1.214 or later. The parameters vary by tool: - * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds). The desktop app’s workspace bash tool also reports `tool_name` as `Bash`, but includes only `bash_command`, `full_command`, and `timeout` + * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, and `dangerouslyDisableSandbox`, plus `git_commit_id` and `git_branch` when a `git commit` command succeeds. `git_commit_id` is the full commit SHA when the commit is the HEAD of the session’s working directory, and git’s abbreviated SHA otherwise. `git_branch` is the branch it was committed on, omitted on a detached HEAD + * For the desktop app’s workspace Bash tool, which also reports `tool_name` as `Bash`: includes only `bash_command`, `full_command`, and `timeout` * For MCP tools: includes `mcp_server_name`, `mcp_tool_name` * For Skill tool: includes `skill_name` * For Agent tool or legacy Task tool: includes `subagent_type`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -445,7 +445,7 @@ `user.account_uuid`| Account UUID (when authenticated)| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) `user.account_id`| Account ID in tagged format matching Anthropic admin APIs (when authenticated), such as `user_01BWBeN28...`| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) `user.id`| Random anonymous identifier generated on first run and persisted in `~/.claude.json`. It contains no personal information and is not derived from your Claude account. Deleting the file produces a new unrelated value on next run.| Always included -`user.email`| User email address (when authenticated via OAuth)| Always included when available +`user.email`| User email address, from your sign-in or, in a [cloud session](</docs/en/claude-code-on-the-web>), from the session’s own credentials| Always included when available `terminal.type`| Terminal type, such as `iTerm.app`, `vscode`, `cursor`, or `tmux`| Always included when detected Keys from `OTEL_RESOURCE_ATTRIBUTES`| Custom attributes you set, such as `department` or `team.id`. See Multi-team organization support| `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES` (default: true) @@ -1227,7 +1227,7 @@ Detect retry exhaustion -Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records the total number of attempts. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15; as of v2.1.199, `CLAUDE_CODE_RETRY_WATCHDOG` raises the default and removes the cap. When the request exhausts all retries on a transient error, `attempt` equals one more than that effective limit: 11 by default, and never more than 16 unless the watchdog is set. A lower value indicates a non-retryable error such as a `400` response. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. +Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records the total number of attempts. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15. On v2.1.199 or later, you can set `CLAUDE_CODE_RETRY_WATCHDOG` to raise the default and remove the cap. When the request exhausts all retries on a transient error, `attempt` equals one more than that effective limit: 11 by default, and never more than 16 unless the watchdog is set. A lower value indicates a non-retryable error such as a `400` response, or a cause with its own smaller retry budget. For example, Claude Code retries a failure to load AWS or Google Cloud credentials at most twice. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. ### @@ -1258,7 +1258,7 @@ Attribute actions to users -The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account, plus `user.id` and the per-session `session.id`. `user.id` is an installation-scoped identifier, except on [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, where it is the IdP subject from the gateway-issued token. MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code doesn’t act under a separate service account; the identity recorded on each event is the developer’s own Claude account, or the developer’s IdP identity on a [Claude apps gateway](</docs/en/claude-apps-gateway>) session. When Claude Code authenticates with a direct API key, or against Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper. Claude apps gateway sessions need none of this: the CLI stamps the IdP identity automatically, as described in Standard attributes. +The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account or, in a [cloud session](</docs/en/claude-code-on-the-web>), when the session’s own credentials carry them, plus `user.id` and the per-session `session.id`. `user.id` is an installation-scoped identifier, except on [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, where it is the IdP subject from the gateway-issued token. MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code doesn’t act under a separate service account; the identity recorded on each event is the developer’s own Claude account, or the developer’s IdP identity on a [Claude apps gateway](</docs/en/claude-apps-gateway>) session. When Claude Code authenticates with a direct API key, or against Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper. Claude apps gateway sessions need none of this: the CLI stamps the IdP identity automatically, as described in Standard attributes. export OTEL_RESOURCE_ATTRIBUTES="enduser.id=jdoe@example.com,enduser.directory_id=S-1-5-21-..." @@ -1398,7 +1398,7 @@ * OpenTelemetry export to your backend is opt-in and requires explicit configuration. For Anthropic’s separate operational telemetry and how to disable it, see [Data usage](</docs/en/data-usage#telemetry-services>) * Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below - * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field + * When authenticated via OAuth, `user.email` is included in telemetry attributes, sent only to the OTel endpoint you configure, never to Anthropic. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` * Assistant response text is not collected by default. Only response length is recorded. To include response text, set `OTEL_LOG_ASSISTANT_RESPONSES=1`. Like all OpenTelemetry data from Claude Code, the response text is sent only to the OTel endpoint you configure, never to Anthropic. When this variable is unset, `OTEL_LOG_USER_PROMPTS` is used as a fallback, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` if you want prompt content without response content * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `tool_decision` and `tool_result` carry the `mcp_server_name`/`mcp_tool_name` pair, host-authored names rather than argument content, even with the flag off. The exception requires Claude Code v2.1.214 or later. This data is sent only to the OTEL endpoint you configure, never to Anthropic. Arguments may still contain sensitive values, so configure your telemetry backend to filter or redact these attributes as needed. When enabled:
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1160,7 +1160,7 @@ * `used_default`: `"true"` when no readable settings source sets `cleanupPeriodDays`, `"false"` otherwise. On complete events, `"true"` means the 30-day default applied * `skip_reason`: Why Claude Code paused the sweep. Present only when `result` is `"skipped"`: * `"user_source_disabled"`: User settings are excluded, for example by the [`--setting-sources`](</docs/en/cli-reference#cli-flags>) flag or the SDK’s [`settingSources`](</docs/en/agent-sdk/typescript#options>) option, and no enabled source provides `cleanupPeriodDays` - * `"settings_unknowable"`: A settings file couldn’t be read or parsed, so `cleanupPeriodDays` may be set to a value Claude Code can’t see + * `"settings_unknowable"`: A settings file couldn’t be read or parsed, so `cleanupPeriodDays` or `desktopSessionCleanupPeriodDays` may be set to a value Claude Code can’t see * `"settings_invalid_key_set"`: Settings have validation errors and `cleanupPeriodDays` or `desktopSessionCleanupPeriodDays` is explicitly set, so falling back to the default could delete or keep files against that setting * `transcripts_deleted`: Number of session transcripts, the top-level `~/.claude/projects/*/*.jsonl` files, that the sweep deleted * `transcripts_exempted_desktop`: Number of transcripts past the retention period that the sweep kept under the [Claude Desktop and Cowork rule](</docs/en/claude-directory#cleaned-up-automatically>). These don’t count toward `files_past_cutoff`. Requires Claude Code v2.1.248 or later
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1149,7 +1149,7 @@ Retention sweep event -Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. When Claude Code can’t safely determine the retention period, it pauses the sweep and emits the event with `result` set to `"skipped"` and a `skip_reason`. When [managed settings](</docs/en/server-managed-settings>) set `cleanupPeriodDays`, the managed value pins the retention period and the sweep runs even when a settings file in a lower-priority scope is broken or invalid. When `managed-settings.json` itself can’t be read or parsed, Claude Code still pauses the sweep unless the [managed tier](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) supplies `cleanupPeriodDays` from elsewhere, such as server-managed settings or a `managed-settings.d/` drop-in beside the broken file. The deletion counter attributes are present only when `result` is `"complete"`. **Event Name** : `claude_code.retention_sweep` **Attributes** : +Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. When Claude Code can’t safely determine the retention period, it pauses the sweep and emits the event with `result` set to `"skipped"` and a `skip_reason`. When [managed settings](</docs/en/server-managed-settings>) set `cleanupPeriodDays`, the managed value pins the retention period and the sweep runs even when a settings file in a lower-priority scope is broken or invalid. When `managed-settings.json` itself can’t be read, Claude Code still pauses the sweep unless the [managed tier](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) supplies `cleanupPeriodDays` from elsewhere, such as server-managed settings or a `managed-settings.d/` drop-in beside the broken file. The deletion counter attributes are present only when `result` is `"complete"`. **Event Name** : `claude_code.retention_sweep` **Attributes** : * All standard attributes * `event.name`: `"retention_sweep"`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -182,7 +182,7 @@ ├── claude_code.tool.execution └── (Agent tool) subagent claude_code.llm_request / claude_code.tool spans -In Agent SDK and `claude -p` sessions, `claude_code.interaction` itself becomes a child of the caller’s span when `TRACEPARENT` is set in the environment. +In Agent SDK and `claude -p` sessions, `claude_code.interaction` itself becomes a child of the caller’s span when `TRACEPARENT` is set in the environment. When a `PreToolUse` hook [defers a tool call](</docs/en/hooks#defer-a-tool-call-for-later>), Claude Code saves the trace context of the turn that deferred it. When you resume the session and the tool re-runs, the tool’s spans join that earlier turn’s trace as children of the turn’s `claude_code.interaction` span. ####
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -64,8 +64,14 @@ * **Protocols** : when you set `OTEL_EXPORTER_OTLP_PROTOCOL`, Claude Code removes every developer-set per-signal protocol. * **Credentials** : when you set `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_CLIENT_KEY`, or `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`, Claude Code removes the developer-set per-signal versions of that variable, plus every developer-set endpoint variable, generic or per-signal, since those credentials would otherwise reach a collector the managed settings didn’t choose. * **Exporter selectors** : `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and the beta `OTEL_TRACES_EXPORTER` follow normal per-key precedence. A developer’s setting can still disable a signal or switch it to the console exporter, so set the selectors in managed settings too if you need them locked. Across [admin sources](</docs/en/managed-settings#precedence-within-the-managed-tier>), `OTEL_LOGS_EXPORTER` follows the [telemetry unit](</docs/en/server-managed-settings#per-key-exceptions-across-managed-sources>) while the other two selectors merge per key. Requires Claude Code v2.1.223 or later. - -Claude Code doesn’t remove per-signal variables that you set in managed settings itself, so you can route one signal to a different collector by setting its variable there, as the SIEM example does. If you set a per-signal credential there, Claude Code removes the developer-set endpoint for that signal. This removal behavior changes where telemetry is delivered, not what Claude Code collects. Before v2.1.217, every variable followed per-key settings precedence independently, so a signal-specific endpoint set in user settings or the shell redirected that signal away from the managed collector. + * **Beta tracing endpoints** : with detailed beta tracing active, Claude Code exports logs and traces to `BETA_TRACING_ENDPOINT` instead of through the logs and traces exporters. Claude Code therefore removes a developer-set `BETA_TRACING_ENDPOINT` whenever any of these managed settings decides either signal’s destination: + * A generic or logs/traces endpoint or credential + * An [`otelHeadersHelper`](</docs/en/settings-reference#otelheadershelper>) + * A logs or traces exporter selector set to `none`, `console`, or empty, values that keep the signal off a collector + * `CLAUDE_CODE_ENABLE_TELEMETRY` turned off +A metrics-only endpoint or credential doesn’t remove it. Before v2.1.251, a developer-set `BETA_TRACING_ENDPOINT` redirected the logs and traces that detailed beta tracing exports even when managed settings pinned the collector. + +Claude Code doesn’t remove per-signal variables that you set in managed settings itself, so you can route one signal to a different collector by setting its variable there, as the SIEM example does. If you set a per-signal credential there, Claude Code removes the developer-set endpoint for that signal. This removal behavior changes where telemetry is delivered, not what Claude Code collects. Before v2.1.217, every variable followed per-key settings precedence independently, so a signal-specific endpoint set in user settings or the shell redirected that signal away from the managed collector. When the desktop app or a [self-hosted environment](</docs/en/self-hosted-environments>) runner launches Claude Code and names an OTLP endpoint in the environment it provides, Claude Code pins the destination the same way: the launcher’s telemetry variables remove developer-set variables exactly as managed settings do. Claude Code doesn’t remove variables that the launcher itself set. Requires Claude Code v2.1.251 or later. ## @@ -260,7 +266,7 @@ `success`| `true` or `false`| `error`| Error category string when execution failed, such as `Error:ENOENT` or `ShellError`. Contains the full error message instead when the gate is set| `OTEL_LOG_TOOL_DETAILS` -**`claude_code.hook`** This span is emitted only when detailed beta tracing is active, which requires `ENABLE_BETA_TRACING_DETAILED=1` and `BETA_TRACING_ENDPOINT` in addition to the trace exporter configuration above. In interactive CLI sessions, this also requires your organization to be allowlisted for the feature. Agent SDK and non-interactive `-p` sessions are not gated. It is not emitted when only `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` is set. +**`claude_code.hook`** This span appears only when detailed beta tracing is active, which requires `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>). Set the pair in your shell, user settings, or managed settings; both variables are ignored in [project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` alone doesn’t produce it. In interactive CLI sessions, detailed beta tracing also requires your organization to be allowlisted for the feature. Agent SDK and non-interactive `-p` sessions don’t require allowlisting. Attribute| Description| Gated by ---|---|--- @@ -1401,7 +1407,9 @@ * `user_prompt` events include the verbatim `command_name` for custom, plugin, and MCP commands * Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`, with the same truncation as `tool_input` * Tool input and output content is not logged in trace spans by default. To include it, set `OTEL_LOG_TOOL_CONTENT=1`. When enabled, span events include full tool input and output content truncated at the content limit (60 KB by default) per attribute. This can include raw file contents from Read tool results and Bash command output. Configure your telemetry backend to filter or redact these attributes as needed - * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES`. With `=1`, each API call emits `api_request_body` and `api_response_body` log events whose `body` attribute is the JSON-serialized payload, truncated at the content limit (60 KB by default). With `=file:<dir>`, untruncated bodies are written to `.request.json` and `.response.json` files under that directory and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. In both modes, bodies contain the full conversation history, including the system prompt, every prior user and assistant turn, and tool results, so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude’s extended-thinking content is always redacted from these bodies regardless of other settings + * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES` in your shell, user settings, or managed settings. It’s ignored in [project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). The bodies contain the full conversation history, including the system prompt, every prior user and assistant turn, and tool results, so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude Code always redacts Claude’s extended-thinking content from these bodies, regardless of other settings. The value you set determines how Claude Code delivers the bodies: + * With `=1`, Claude Code emits `api_request_body` and `api_response_body` log events for each API call. The events’ `body` attribute carries the JSON-serialized payload, truncated at the content limit (60 KB by default) + * With `=file:<dir>`, Claude Code writes untruncated bodies to `.request.json` and `.response.json` files under that directory, and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1155,8 +1155,9 @@ * `skip_reason`: Why Claude Code paused the sweep. Present only when `result` is `"skipped"`: * `"user_source_disabled"`: User settings are excluded, for example by the [`--setting-sources`](</docs/en/cli-reference#cli-flags>) flag or the SDK’s [`settingSources`](</docs/en/agent-sdk/typescript#options>) option, and no enabled source provides `cleanupPeriodDays` * `"settings_unknowable"`: A settings file couldn’t be read or parsed, so `cleanupPeriodDays` may be set to a value Claude Code can’t see - * `"settings_invalid_key_set"`: Settings have validation errors and `cleanupPeriodDays` is explicitly set, so falling back to the default could delete files the setting was meant to keep + * `"settings_invalid_key_set"`: Settings have validation errors and `cleanupPeriodDays` or `desktopSessionCleanupPeriodDays` is explicitly set, so falling back to the default could delete or keep files against that setting * `transcripts_deleted`: Number of session transcripts, the top-level `~/.claude/projects/*/*.jsonl` files, that the sweep deleted + * `transcripts_exempted_desktop`: Number of transcripts past the retention period that the sweep kept under the [Claude Desktop and Cowork rule](</docs/en/claude-directory#cleaned-up-automatically>). These don’t count toward `files_past_cutoff`. Requires Claude Code v2.1.248 or later * `session_files_deleted`: Number of artifacts the session-files sweep deleted: transcripts plus per-session companion files such as sidecars, recordings, and tool results * `artifacts_deleted`: Total items the sweep deleted across the data directories it covers, including the session files. Some sweeps count a whole removed directory tree as one item and a few cleanup passes don’t contribute to the counter, so treat the value as a floor rather than an exact file count * `files_retained_fresh`: Files inspected and left in place because they’re still within the retention period. Only per-file sweeps count these, so the value is a floor; a nonzero value is the normal steady state
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -29,7 +29,7 @@ # 6. Run Claude Code claude -To verify a setup that exports metrics, check your backend for the `claude_code.session.count` metric, which Claude Code emits when a session starts. To verify a logs-only setup, submit a prompt and check for the `claude_code.user_prompt` event. If nothing arrives, run `claude --debug` and check the debug log for OTel export errors. For full configuration options, see the [OpenTelemetry specification](<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options>). +To verify a setup that exports metrics, check your backend for the `claude_code.session.count` metric, which Claude Code emits when a session starts. To verify a logs-only setup, submit a prompt and check for the `claude_code.user_prompt` event. If nothing arrives, run `claude --debug` and check the debug log. Claude Code reports failures from the exporters you configure as `[3P telemetry]` errors, where 3P means third-party. Lines prefixed `[Anthropic telemetry]` describe [Anthropic’s separate operational telemetry](</docs/en/data-usage#telemetry-services>) and don’t indicate a problem with your setup. For full configuration options, see the [OpenTelemetry specification](<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options>). ## @@ -1228,7 +1228,7 @@ Event analysis -The event data provides detailed insights into Claude Code interactions: **Tool usage patterns** : analyze tool result events to identify: +The event data describes each Claude Code interaction in detail: **Tool usage patterns** : analyze tool result events to identify: * Most frequently used tools * Tool success rates @@ -1314,7 +1314,7 @@ } } -To confirm events arrive, submit a prompt in a session running under this configuration and check your SIEM for the `claude_code.user_prompt` event. If nothing arrives, run `claude --debug` and check the debug log for OTel export errors. +To confirm events arrive, submit a prompt in a session running under this configuration and check your SIEM for the `claude_code.user_prompt` event. If nothing arrives, run `claude --debug` and check the debug log for `[3P telemetry]` export errors. ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1143,7 +1143,7 @@ Retention sweep event -Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. When Claude Code can’t safely determine the retention period, it pauses the sweep and emits the event with `result` set to `"skipped"` and a `skip_reason`. When [managed settings](</docs/en/server-managed-settings>) set `cleanupPeriodDays`, the managed value pins the retention period and the sweep runs even when a settings file in a lower-priority scope is broken or invalid. When `managed-settings.json` itself can’t be read or parsed, Claude Code still pauses the sweep unless the [managed source it selects](</docs/en/server-managed-settings#settings-precedence>) supplies `cleanupPeriodDays` from elsewhere, such as server-managed settings or a `managed-settings.d/` drop-in beside the broken file. The deletion counter attributes are present only when `result` is `"complete"`. **Event Name** : `claude_code.retention_sweep` **Attributes** : +Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. When Claude Code can’t safely determine the retention period, it pauses the sweep and emits the event with `result` set to `"skipped"` and a `skip_reason`. When [managed settings](</docs/en/server-managed-settings>) set `cleanupPeriodDays`, the managed value pins the retention period and the sweep runs even when a settings file in a lower-priority scope is broken or invalid. When `managed-settings.json` itself can’t be read or parsed, Claude Code still pauses the sweep unless the [managed tier](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) supplies `cleanupPeriodDays` from elsewhere, such as server-managed settings or a `managed-settings.d/` drop-in beside the broken file. The deletion counter attributes are present only when `result` is `"complete"`. **Event Name** : `claude_code.retention_sweep` **Attributes** : * All standard attributes * `event.name`: `"retention_sweep"`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1330,9 +1330,9 @@ For metrics - * **Time series databases (for example, Prometheus)** : Rate calculations, aggregated metrics - * **Columnar stores (for example, ClickHouse)** : Complex queries, unique user analysis - * **Full-featured observability platforms (for example, Honeycomb, Datadog, Grafana Cloud)** : Advanced querying, visualization, alerting + * **Time series databases** : Rate calculations, aggregated metrics + * **Columnar stores** : Complex queries, unique user analysis + * **Full-featured observability platforms** : Advanced querying, visualization, alerting ### @@ -1340,9 +1340,9 @@ For events/logs - * **Log aggregation systems (for example, Elasticsearch, Loki)** : Full-text search, log analysis - * **Columnar stores (for example, ClickHouse)** : Structured event analysis - * **Full-featured observability platforms (for example, Honeycomb, Datadog, Grafana Cloud)** : Correlation between metrics and events + * **Log aggregation systems** : Full-text search, log analysis + * **Columnar stores** : Structured event analysis + * **Full-featured observability platforms** : Correlation between metrics and events ### @@ -1352,8 +1352,8 @@ Choose a backend that supports distributed trace storage and span correlation: - * **Distributed tracing systems (for example, Jaeger, Zipkin, Grafana Tempo)** : Span visualization, request waterfalls, latency analysis - * **Full-featured observability platforms (for example, Honeycomb, Datadog, Grafana Cloud)** : Trace search and correlation with metrics and logs + * **Distributed tracing systems** : Span visualization, request waterfalls, latency analysis + * **Full-featured observability platforms** : Trace search and correlation with metrics and logs For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries.
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -877,7 +877,7 @@ * `duration_ms`: Connection attempt duration in milliseconds * `error_code`: Error code when the connection failed * `is_plugin`: `true` when the server is provided by a plugin, `false` otherwise - * `plugin_id_hash` (when `is_plugin` is `true`): Stable hash of the plugin name and marketplace, for grouping events by plugin without exposing the name + * `plugin_id_hash` (when `is_plugin` is `true`): Stable hash of the plugin name and marketplace, for grouping events by plugin without exposing the name. Claude Code computes it as described under the plugin loaded event * `plugin.name` (when `is_plugin` is `true`): Name of the plugin that provides the server. For third-party plugins this is the literal string `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1`; this protects third-party plugin names from appearing in logs by default. Plugins from official Anthropic sources are always identified by name. The `plugin_id_hash` and `plugin.name` attributes flow to your own monitoring backend and are not sent to Anthropic * `server_name` (when `OTEL_LOG_TOOL_DETAILS=1`): Configured server name * `error` (when `OTEL_LOG_TOOL_DETAILS=1`): Full error message when the connection failed @@ -930,9 +930,9 @@ * `plugin.name`: name of the plugin. For plugins outside the official marketplace and built-in bundle the value is `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` * `marketplace.name`: marketplace the plugin was installed from, when known. Redacted to `"third-party"` under the same condition as `plugin.name` * `plugin.version`: version from the plugin manifest. Included only when the name is not redacted and the manifest declares a version - * `plugin.scope`: provenance category for the plugin: `"official"`, `"org"`, `"user-local"`, or `"default-bundle"` - * `enabled_via`: how the plugin came to be enabled: `"default-enable"`, `"org-policy"`, `"seed-mount"`, or `"user-install"` - * `plugin_id_hash`: deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count how many distinct third-party plugins are loaded across your fleet without recording their names + * `plugin.scope`: provenance category for the plugin: `"official"`, `"community"`, `"org"`, `"user-local"`, or `"default-bundle"` + * `enabled_via`: how the plugin came to be enabled: `"default-enable"`, `"org-policy"`, `"admin-install"`, `"seed-mount"`, or `"user-install"`. The `"admin-install"` value means the plugin is set to required or auto-install for your organization in [**Organization settings > Plugins**](<https://claude.ai/admin-settings/plugins>). Before v2.1.246, Claude Code reported these plugins as `"user-install"` or `"seed-mount"` + * `plugin_id_hash`: deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count the distinct third-party plugins loaded across your fleet without recording their names. For [plugins synced from claude.ai](</docs/en/plugins-reference#synced-plugins>), Claude Code hashes the plugin name with the marketplace name that claude.ai reports for the plugin, or with `synced` otherwise. Before v2.1.246, Claude Code didn’t use the marketplace name claude.ai reports in the hash * `has_hooks`: whether the plugin contributes hooks * `has_mcp`: whether the plugin contributes MCP servers * `host_owned_mcp`: `true` when the SDK host manages this plugin’s MCP connections and Claude Code skipped reading the plugin’s MCP server configuration, `false` otherwise. Requires Claude Code v2.1.172 or later @@ -1012,7 +1012,7 @@ * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. Requires Claude Code v2.1.169 or later * `hook_matcher` (when `OTEL_LOG_TOOL_DETAILS=1`): the matcher string from the hook configuration, when one is set * `plugin.name` (when `hook_source` is `"pluginHook"`): name of the contributing plugin. For plugins outside the official marketplace and built-in bundle the value is `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` - * `plugin_id_hash` (when `hook_source` is `"pluginHook"`): deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count distinct contributing plugins without recording their names + * `plugin_id_hash` (when `hook_source` is `"pluginHook"`): deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count distinct contributing plugins without recording their names. Claude Code computes it as described under the plugin loaded event ####
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -37,7 +37,7 @@ Administrator configuration -Administrators can configure OpenTelemetry settings for all users through the [managed settings file](</docs/en/settings#settings-files>). See the [settings precedence](</docs/en/settings#settings-precedence>) for more information about how settings are applied. Example managed settings configuration: +Administrators can configure OpenTelemetry settings for all users through the [managed settings file](</docs/en/managed-settings#delivery-mechanisms>). See the [settings precedence](</docs/en/settings#settings-precedence>) for more information about how settings are applied. Example managed settings configuration: { "env": { @@ -63,7 +63,7 @@ * **Endpoints** : when you set `OTEL_EXPORTER_OTLP_ENDPOINT`, Claude Code removes every developer-set per-signal endpoint. Developers can’t point one signal at a different collector, so you don’t need to also set the per-signal endpoint variables in managed settings. * **Protocols** : when you set `OTEL_EXPORTER_OTLP_PROTOCOL`, Claude Code removes every developer-set per-signal protocol. * **Credentials** : when you set `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_CLIENT_KEY`, or `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`, Claude Code removes the developer-set per-signal versions of that variable, plus every developer-set endpoint variable, generic or per-signal, since those credentials would otherwise reach a collector the managed settings didn’t choose. - * **Exporter selectors** : `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and the beta `OTEL_TRACES_EXPORTER` follow normal per-key precedence. A developer’s setting can still disable a signal or switch it to the console exporter, so set the selectors in managed settings too if you need them locked. Across [admin sources](</docs/en/settings#precedence-within-the-managed-tier>), `OTEL_LOGS_EXPORTER` follows the [telemetry unit](</docs/en/server-managed-settings#per-key-exceptions-across-managed-sources>) while the other two selectors merge per key. Requires Claude Code v2.1.223 or later. + * **Exporter selectors** : `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and the beta `OTEL_TRACES_EXPORTER` follow normal per-key precedence. A developer’s setting can still disable a signal or switch it to the console exporter, so set the selectors in managed settings too if you need them locked. Across [admin sources](</docs/en/managed-settings#precedence-within-the-managed-tier>), `OTEL_LOGS_EXPORTER` follows the [telemetry unit](</docs/en/server-managed-settings#per-key-exceptions-across-managed-sources>) while the other two selectors merge per key. Requires Claude Code v2.1.223 or later. Claude Code doesn’t remove per-signal variables that you set in managed settings itself, so you can route one signal to a different collector by setting its variable there, as the SIEM example does. If you set a per-signal credential there, Claude Code removes the developer-set endpoint for that signal. This removal behavior changes where telemetry is delivered, not what Claude Code collects. Before v2.1.217, every variable followed per-key settings precedence independently, so a signal-specific endpoint set in user settings or the shell redirected that signal away from the managed collector. @@ -1143,7 +1143,7 @@ Retention sweep event -Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. When Claude Code can’t safely determine the retention period, it pauses the sweep and emits the event with `result` set to `"skipped"` and a `skip_reason`. When [managed settings](</docs/en/server-managed-settings>) set `cleanupPeriodDays`, the managed value pins the retention period and the sweep runs even when a settings file in a lower-priority scope is broken or invalid; a managed settings file that itself can’t be read or parsed still pauses the sweep. The deletion counter attributes are present only when `result` is `"complete"`. **Event Name** : `claude_code.retention_sweep` **Attributes** : +Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. When Claude Code can’t safely determine the retention period, it pauses the sweep and emits the event with `result` set to `"skipped"` and a `skip_reason`. When [managed settings](</docs/en/server-managed-settings>) set `cleanupPeriodDays`, the managed value pins the retention period and the sweep runs even when a settings file in a lower-priority scope is broken or invalid. When `managed-settings.json` itself can’t be read or parsed, Claude Code still pauses the sweep unless the [managed source it selects](</docs/en/server-managed-settings#settings-precedence>) supplies `cleanupPeriodDays` from elsewhere, such as server-managed settings or a `managed-settings.d/` drop-in beside the broken file. The deletion counter attributes are present only when `result` is `"complete"`. **Event Name** : `claude_code.retention_sweep` **Attributes** : * All standard attributes * `event.name`: `"retention_sweep"`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -815,7 +815,7 @@ * `"config"`: Decided automatically without prompting, based on project settings, allow or deny rules in the user’s personal settings, enterprise managed policy, `--allowedTools` or `--disallowedTools` flags, the active permission mode, a session-scoped grant from an earlier prompt in the same interactive CLI session, or because the tool is inherently safe. The event doesn’t indicate which of these sources matched. Claude Code also reports `"config"` when the permission prompt request itself fails, for example when the Agent SDK’s [`canUseTool`](</docs/en/agent-sdk/typescript#canusetool>) callback or the [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) tool returns an invalid result, or when the input stream closes while the request is pending. Before v2.1.216, Claude Code reported these failures as `"user_reject"`. * `"hook"`: A `PreToolUse` or `PermissionRequest` hook returned the decision. * `"user_permanent"`: Emitted when the user chose “Yes, and don’t ask again for …” at a permission prompt, which saves an allow rule to their personal settings. In the interactive CLI this is emitted only for that choice itself; later calls that match the saved rule emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the initial choice and later rule matches emit `"user_permanent"`. Treated as an accept. - * `"user_temporary"`: Emitted when the user chose “Yes” at a permission prompt for a one-time approval, or chose one of the ”… during this session” options on a file edit or read prompt. In the interactive CLI this is emitted only for the choice itself; later calls allowed by that session-scoped grant emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the choice and later matches emit `"user_temporary"`. Treated as an accept. + * `"user_temporary"`: Emitted when the user chose “Yes” at a permission prompt for a one-time approval, or chose an option that grants access for the rest of the session on a file edit or read prompt. In the interactive CLI this is emitted only for the choice itself; later calls allowed by that session-scoped grant emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the choice and later matches emit `"user_temporary"`. Treated as an accept. * `"user_abort"`: Emitted when the user dismissed the permission prompt without answering. In Agent SDK and non-interactive `-p` sessions, this includes interrupting the turn while a `canUseTool` or `--permission-prompt-tool` permission request is pending; before v2.1.216, Claude Code reported that interrupt as `"user_reject"`. Treated as a reject. * `"user_reject"`: Emitted when the user chose “No” when prompted. In the interactive CLI this is emitted only for that choice itself; calls that match a deny rule in the user’s personal settings emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, calls that match a deny rule in personal settings emit `"user_reject"`. Treated as a reject. * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters. Same shape as the Tool result event, minus post-execution fields such as `git_commit_id`. Values may differ from `tool_result` for an accepted call if the permission decision rewrites the tool input via `updatedInput`. Use this attribute to see which command was rejected when `decision` is `"reject"`.
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -63,7 +63,7 @@ * **Endpoints** : when you set `OTEL_EXPORTER_OTLP_ENDPOINT`, Claude Code removes every developer-set per-signal endpoint. Developers can’t point one signal at a different collector, so you don’t need to also set the per-signal endpoint variables in managed settings. * **Protocols** : when you set `OTEL_EXPORTER_OTLP_PROTOCOL`, Claude Code removes every developer-set per-signal protocol. * **Credentials** : when you set `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_CLIENT_KEY`, or `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`, Claude Code removes the developer-set per-signal versions of that variable, plus every developer-set endpoint variable, generic or per-signal, since those credentials would otherwise reach a collector the managed settings didn’t choose. - * **Exporter selectors** : `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and the beta `OTEL_TRACES_EXPORTER` follow normal per-key precedence. A developer’s setting can still disable a signal or switch it to the console exporter, so set the selectors in managed settings too if you need them locked. Across [admin sources](</docs/en/settings#settings-precedence>), `OTEL_LOGS_EXPORTER` follows the [telemetry unit](</docs/en/server-managed-settings#per-key-exceptions-across-managed-sources>) while the other two selectors merge per key. Requires Claude Code v2.1.223 or later. + * **Exporter selectors** : `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and the beta `OTEL_TRACES_EXPORTER` follow normal per-key precedence. A developer’s setting can still disable a signal or switch it to the console exporter, so set the selectors in managed settings too if you need them locked. Across [admin sources](</docs/en/settings#precedence-within-the-managed-tier>), `OTEL_LOGS_EXPORTER` follows the [telemetry unit](</docs/en/server-managed-settings#per-key-exceptions-across-managed-sources>) while the other two selectors merge per key. Requires Claude Code v2.1.223 or later. Claude Code doesn’t remove per-signal variables that you set in managed settings itself, so you can route one signal to a different collector by setting its variable there, as the SIEM example does. If you set a per-signal credential there, Claude Code removes the developer-set endpoint for that signal. This removal behavior changes where telemetry is delivered, not what Claude Code collects. Before v2.1.217, every variable followed per-key settings precedence independently, so a signal-specific endpoint set in user settings or the shell redirected that signal away from the managed collector. @@ -79,7 +79,7 @@ Common configuration variables -These variables configure exporters, endpoints, and export behavior for all deployments. A per-signal variable overrides its generic counterpart. On machines with managed settings, see How managed settings lock the OTLP destination for what Claude Code removes. +These variables configure exporters, endpoints, and export behavior for all deployments. If you set a per-signal endpoint or protocol variable, such as `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`, Claude Code uses it instead of the generic variable for that signal. If you set a per-signal headers variable, such as `OTEL_EXPORTER_OTLP_METRICS_HEADERS`, Claude Code merges it with the generic `OTEL_EXPORTER_OTLP_HEADERS` for that signal. On machines with managed settings, see How managed settings lock the OTLP destination for what Claude Code removes. Environment Variable| Description| Example Values ---|---|--- @@ -93,6 +93,8 @@ `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL`| Protocol for logs, overrides general setting| `grpc`, `http/json`, `http/protobuf` `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`| OTLP logs endpoint, overrides general setting| `http://localhost:4318/v1/logs` `OTEL_EXPORTER_OTLP_HEADERS`| Authentication headers for OTLP| `Authorization=Bearer token` +`OTEL_EXPORTER_OTLP_METRICS_HEADERS`| Authentication headers for metrics, merged with the general headers| `Authorization=Bearer token` +`OTEL_EXPORTER_OTLP_LOGS_HEADERS`| Authentication headers for logs, merged with the general headers| `Authorization=Bearer token` `OTEL_METRIC_EXPORT_INTERVAL`| Export interval in milliseconds (default: 60000)| `5000`, `60000` `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable @@ -145,7 +147,7 @@ Traces (beta) -Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend. Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the common OTLP configuration for endpoint, protocol, headers, and mTLS. On machines with managed settings, Claude Code may remove developer-set `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` and `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` variables at startup. +Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend. Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the common OTLP configuration for endpoint, protocol, headers, and mTLS. On machines with managed settings, Claude Code may remove developer-set per-signal credentials and endpoints at startup. Environment Variable| Description| Example Values ---|---|--- @@ -153,6 +155,7 @@ `OTEL_TRACES_EXPORTER`| Traces exporter types, comma-separated. Use `none` to disable| `console`, `otlp`, `none` `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL`| Protocol for traces, overrides `OTEL_EXPORTER_OTLP_PROTOCOL`| `grpc`, `http/json`, `http/protobuf` `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`| OTLP traces endpoint, overrides `OTEL_EXPORTER_OTLP_ENDPOINT`| `http://localhost:4318/v1/traces` +`OTEL_EXPORTER_OTLP_TRACES_HEADERS`| Authentication headers for traces, merged with `OTEL_EXPORTER_OTLP_HEADERS`| `Authorization=Bearer token` `OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000` Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. When tracing is active and Claude Code is connected directly to the Anthropic API, each model request carries a W3C `traceparent` header set to the `claude_code.llm_request` span’s context, and the API’s `traceresponse` header is recorded as a span link. Together these connect Claude Code’s client-side spans to the server-side trace through any compliant intermediary. Outbound HTTP MCP requests carry `traceparent` the same way. The header is not sent to third-party providers. By default, the `traceparent` header on model and HTTP MCP requests is sent only when `ANTHROPIC_BASE_URL` is unset or points at the Anthropic API, since some proxies reject unrecognized headers. The subprocess `TRACEPARENT` variable is controlled by the same switch for consistency. If you run Claude Code through a custom `ANTHROPIC_BASE_URL` proxy and want trace context propagated, set `CLAUDE_CODE_PROPAGATE_TRACEPARENT=1`. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. The inbound trace context also applies to events. In Agent SDK and `-p` sessions with `TRACEPARENT` set, each OTLP event log record carries `trace_id` and `span_id` values that join it to your application’s trace, even when the traces exporter isn’t configured, so your logging backend can correlate events with the rest of the trace. A record emitted while an interaction is active carries the interaction span’s IDs, even when Claude Code emits it outside the span’s async context, such as in a permission prompt callback or for a record buffered during startup and exported later. A record emitted with no active interaction span carries the inbound `TRACEPARENT` IDs directly. Before v2.1.214, records emitted outside the span’s async context carried the inbound `TRACEPARENT` IDs instead of the span’s IDs. Before v2.1.212, event records emitted outside an active span didn’t carry `trace_id` or `span_id`. @@ -279,7 +282,7 @@ Dynamic headers -For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically. Dynamic headers apply only to the `http/protobuf` and `http/json` protocols. The `grpc` exporter uses only the static `OTEL_EXPORTER_OTLP_HEADERS` value. +For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically. Dynamic headers apply only to the `http/protobuf` and `http/json` protocols. With the `grpc` protocol, Claude Code uses only the static headers variables, `OTEL_EXPORTER_OTLP_HEADERS` and its per-signal variants. #### @@ -696,7 +699,7 @@ * `cache_read_tokens`: Number of tokens read from cache * `cache_creation_tokens`: Number of tokens used for cache creation * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. - * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header. Matches the same attribute on the `llm_request` trace span. Absent on third-party provider backends and when the request was retried through the non-streaming fallback. Requires Claude Code v2.1.214 or later + * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header; see the event correlation attributes table for when it’s present. Requires Claude Code v2.1.214 or later * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model doesn’t support effort. @@ -720,7 +723,7 @@ * `duration_ms`: Request duration in milliseconds * `attempt`: Total number of attempts made, including the initial request (`1` means no retries occurred) * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. - * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header. Available even when a failure such as a timeout or connection error never produced a server `request_id`. Absent on third-party provider backends and when the request was retried through the non-streaming fallback. Requires Claude Code v2.1.214 or later + * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header. Available even when a failure such as a timeout or connection error never produced a server `request_id`; see the event correlation attributes table for when it’s present. Requires Claude Code v2.1.214 or later * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when the model doesn’t support effort. @@ -969,7 +972,7 @@ * `event.name`: `"at_mention"` * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session - * `mention_type`: Type of mention (`"file"`, `"directory"`, `"agent"`, `"mcp_resource"`) + * `mention_type`: Type of mention (`"file"`, `"directory"`, `"agent"`, `"mcp_resource"`, `"peer"`). The `"peer"` value means you mentioned [one of your other Claude Code sessions](</docs/en/cross-session-messaging>). Requires Claude Code v2.1.232 or later * `success`: Whether the mention resolved successfully (`"true"` or `"false"`) ####
modified
Show diff (134 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1,4 +1,4 @@ -Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, events via the logs/events protocol, and optionally distributed traces via the traces protocol. Configure your metrics, logs, and traces backends to match your monitoring requirements. +Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, events via the logs/events protocol, and optionally distributed traces via the traces protocol. ## @@ -22,15 +22,13 @@ # 4. Set authentication (if required) export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-token" - # 5. For debugging: reduce export intervals + # 5. For debugging: reduce export intervals, and reset them for production use export OTEL_METRIC_EXPORT_INTERVAL=10000 # 10 seconds (default: 60000ms) export OTEL_LOGS_EXPORT_INTERVAL=5000 # 5 seconds (default: 5000ms) # 6. Run Claude Code claude -The default export intervals are 60 seconds for metrics and 5 seconds for logs. During setup, you may want to use shorter intervals for debugging purposes. Remember to reset these for production use. - To verify a setup that exports metrics, check your backend for the `claude_code.session.count` metric, which Claude Code emits when a session starts. To verify a logs-only setup, submit a prompt and check for the `claude_code.user_prompt` event. If nothing arrives, run `claude --debug` and check the debug log for OTel export errors. For full configuration options, see the [OpenTelemetry specification](<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options>). ## @@ -39,7 +37,7 @@ Administrator configuration -Administrators can configure OpenTelemetry settings for all users through the [managed settings file](</docs/en/settings#settings-files>). This allows for centralized control of telemetry settings across an organization. See the [settings precedence](</docs/en/settings#settings-precedence>) for more information about how settings are applied. Example managed settings configuration: +Administrators can configure OpenTelemetry settings for all users through the [managed settings file](</docs/en/settings#settings-files>). See the [settings precedence](</docs/en/settings#settings-precedence>) for more information about how settings are applied. Example managed settings configuration: { "env": { @@ -51,8 +49,6 @@ "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer example-token" } } - -Managed settings can be distributed via MDM (Mobile Device Management) or other device management solutions. Environment variables defined in the managed settings file have high precedence and can’t be overridden by users. Claude Code doesn’t pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool doesn’t inherit Claude Code’s exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry. @@ -141,7 +137,7 @@ `OTEL_METRICS_INCLUDE_ENTRYPOINT`| Include app.entrypoint attribute in metrics| `false`| `true` `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES`| Include keys from `OTEL_RESOURCE_ATTRIBUTES` as attributes on metric datapoints| `true`| `false` -These variables help control the cardinality of metrics, which affects storage requirements and query performance in your metrics backend. Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. +Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. ### @@ -387,7 +383,7 @@ export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=prometheus -To send metrics to multiple exporters: +On a [self-hosted environment](</docs/en/self-hosted-environments-reference#pass-through-session-child-metrics>), the session binds port 9464 only at the runner’s default capacity of one. At higher capacity, the runner re-exposes session counters and gauges on its own `/metrics` endpoint instead. To send metrics to multiple exporters: export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=console,otlp @@ -611,8 +607,6 @@ * `message.uuid` on `user_prompt` and `assistant_response` * `request_id` on the API events, persisted as `requestId` on the transcript’s assistant entries * `tool_use_id` on `tool_result` and `tool_decision` events - -`prompt.id` is intentionally excluded from metrics because each prompt generates a unique ID, which would create an ever-growing number of time series. Use it for event-level analysis and audit trails only. #### @@ -1102,6 +1096,30 @@ ​ +Subagent completed event + +Logged when a [subagent](</docs/en/sub-agents>) finishes and returns its result to the conversation that started it. Use it to roll up tool use and run time by subagent type; for token or cost rollups, use the token counter and cost counter filtered to `query_source` `"subagent"`, since this event’s `total_tokens` covers only the final request. The `"subagent"` category also counts requests from agent-based hooks, which emit no subagent event. **Event Name** : `claude_code.subagent_completed` **Attributes** : + + * All standard attributes + * `event.name`: `"subagent_completed"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `agent_type`: The subagent type. Built-in agent names and agents from official-marketplace plugins appear verbatim; other agent names are replaced with `"custom"` unless `OTEL_LOG_TOOL_DETAILS=1` is set + * `agent.source`: Where the agent definition came from: `built-in`, `plugin`, or the settings source that defined a custom agent, such as `userSettings` or `projectSettings` + * `is_built_in`: Whether the subagent is a built-in agent type + * `is_async`: Whether the subagent ran in the [background](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) + * `total_tokens`: The token footprint of the subagent’s final API request: that one request’s input, cache creation, cache read, and output tokens, roughly the subagent’s context size at completion. Not a sum across the run + * `total_tool_uses`: Number of tool calls the subagent made across the whole run + * `duration_ms`: Run time in milliseconds + * `model`: The model the subagent was resolved to run + * `final_model`: The model that produced the subagent’s final response, which differs from `model` after a mid-run switch such as a fallback. Requires Claude Code v2.1.212 or later + * `model_swapped`: Whether more than one model served the subagent’s requests. Requires Claude Code v2.1.212 or later + * `plugin_id_hash`, `plugin.name`: Present for plugin-provided agents. Official-marketplace plugin names appear verbatim; other plugin names are replaced with `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` is set + +#### + +​ + Feedback survey event Logged when a session quality survey is shown or answered. See [Session quality surveys](</docs/en/data-usage#session-quality-surveys>) for what the surveys collect and how to control them. **Event Name** : `claude_code.feedback_survey` **Attributes** : @@ -1115,6 +1133,32 @@ * `survey_type`: Which survey produced the event. `"session"` is the “How is Claude doing?” rating prompt * `response`: The user’s selection on `responded` events * `enabled_via_override`: `true` when [`CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL`](</docs/en/env-vars>) is set. Emitted as a boolean, not a string. Present on `session` survey events. Filter on this attribute to confirm the override is applied across a fleet + +#### + +​ + +Retention sweep event + +Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. When Claude Code can’t safely determine the retention period, it pauses the sweep and emits the event with `result` set to `"skipped"` and a `skip_reason`. When [managed settings](</docs/en/server-managed-settings>) set `cleanupPeriodDays`, the managed value pins the retention period and the sweep runs even when a settings file in a lower-priority scope is broken or invalid; a managed settings file that itself can’t be read or parsed still pauses the sweep. The deletion counter attributes are present only when `result` is `"complete"`. **Event Name** : `claude_code.retention_sweep` **Attributes** : + + * All standard attributes + * `event.name`: `"retention_sweep"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `result`: `"complete"` when the sweep ran, `"skipped"` when Claude Code paused it + * `period_days`: The `cleanupPeriodDays` value from merged settings, in days, or `30` when no source sets it. On skipped events, the value the sweep would have used, computed from the settings sources Claude Code could read + * `used_default`: `"true"` when no readable settings source sets `cleanupPeriodDays`, `"false"` otherwise. On complete events, `"true"` means the 30-day default applied + * `skip_reason`: Why Claude Code paused the sweep. Present only when `result` is `"skipped"`: + * `"user_source_disabled"`: User settings are excluded, for example by the [`--setting-sources`](</docs/en/cli-reference#cli-flags>) flag or the SDK’s [`settingSources`](</docs/en/agent-sdk/typescript#options>) option, and no enabled source provides `cleanupPeriodDays` + * `"settings_unknowable"`: A settings file couldn’t be read or parsed, so `cleanupPeriodDays` may be set to a value Claude Code can’t see + * `"settings_invalid_key_set"`: Settings have validation errors and `cleanupPeriodDays` is explicitly set, so falling back to the default could delete files the setting was meant to keep + * `transcripts_deleted`: Number of session transcripts, the top-level `~/.claude/projects/*/*.jsonl` files, that the sweep deleted + * `session_files_deleted`: Number of artifacts the session-files sweep deleted: transcripts plus per-session companion files such as sidecars, recordings, and tool results + * `artifacts_deleted`: Total items the sweep deleted across the data directories it covers, including the session files. Some sweeps count a whole removed directory tree as one item and a few cleanup passes don’t contribute to the counter, so treat the value as a floor rather than an exact file count + * `files_retained_fresh`: Files inspected and left in place because they’re still within the retention period. Only per-file sweeps count these, so the value is a floor; a nonzero value is the normal steady state + * `files_past_cutoff`: Files older than the retention period that the sweep failed to delete, for example because of a permission error or a file held open. A value above zero means files outlived the configured retention period; zero isn’t proof that none did, because a failed removal of a whole directory counts toward `error_count` instead + * `error_count`: Number of errors the sweep encountered while listing or deleting files ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -67,7 +67,7 @@ * **Endpoints** : when you set `OTEL_EXPORTER_OTLP_ENDPOINT`, Claude Code removes every developer-set per-signal endpoint. Developers can’t point one signal at a different collector, so you don’t need to also set the per-signal endpoint variables in managed settings. * **Protocols** : when you set `OTEL_EXPORTER_OTLP_PROTOCOL`, Claude Code removes every developer-set per-signal protocol. * **Credentials** : when you set `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_CLIENT_KEY`, or `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`, Claude Code removes the developer-set per-signal versions of that variable, plus every developer-set endpoint variable, generic or per-signal, since those credentials would otherwise reach a collector the managed settings didn’t choose. - * **Exporter selectors** : `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and the beta `OTEL_TRACES_EXPORTER` follow normal per-key precedence. A developer’s setting can still disable a signal or switch it to the console exporter, so set the selectors in managed settings too if you need them locked. + * **Exporter selectors** : `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and the beta `OTEL_TRACES_EXPORTER` follow normal per-key precedence. A developer’s setting can still disable a signal or switch it to the console exporter, so set the selectors in managed settings too if you need them locked. Across [admin sources](</docs/en/settings#settings-precedence>), `OTEL_LOGS_EXPORTER` follows the [telemetry unit](</docs/en/server-managed-settings#per-key-exceptions-across-managed-sources>) while the other two selectors merge per key. Requires Claude Code v2.1.223 or later. Claude Code doesn’t remove per-signal variables that you set in managed settings itself, so you can route one signal to a different collector by setting its variable there, as the SIEM example does. If you set a per-signal credential there, Claude Code removes the developer-set endpoint for that signal. This removal behavior changes where telemetry is delivered, not what Claude Code collects. Before v2.1.217, every variable followed per-key settings precedence independently, so a signal-specific endpoint set in user settings or the shell redirected that signal away from the managed collector.
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -540,8 +540,8 @@ * `skill.name`: Skill active for the request, set by the Skill tool, a `/` command, or inherited by a spawned subagent. Built-in, bundled, user-defined, and official-marketplace plugin skill names appear verbatim. Third-party plugin skill names are replaced with `"third-party"`. Absent when no skill is active. * `plugin.name`: Owning plugin when the active skill or subagent is provided by a plugin. Official-marketplace plugin names appear verbatim. Third-party plugin names are replaced with `"third-party"`. Absent when neither the skill nor the subagent has an owning plugin. * `marketplace.name`: Marketplace the owning plugin was installed from. Only emitted for official-marketplace plugins. Absent otherwise. - * `mcp_server.name`: MCP server whose tool ran in the turn that produced this request. Built-in, claude.ai-proxied, and official-registry server names appear verbatim. User-configured server names are replaced with `"custom"`. Absent when no MCP tool ran. - * `mcp_tool.name`: MCP tool that ran in the turn that produced this request, with the same redaction as `mcp_server.name`. Absent when no MCP tool ran. + * `mcp_server.name`: MCP server whose tool result this request consumed. Built-in, claude.ai-proxied, and official-registry server names appear verbatim. User-configured server names are replaced with `"custom"`. Absent when the request consumed no MCP tool result. Before v2.1.222, Claude Code set this attribute on every request after an MCP tool call, not only on requests that consumed a tool result, so dashboards that aggregate it show a step down after you upgrade. + * `mcp_tool.name`: MCP tool whose result this request consumed, with the same redaction and version behavior as `mcp_server.name`. Absent when the request consumed no MCP tool result. ####
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -60,14 +60,16 @@ ​ -Managed endpoints govern signal-specific endpoints - -A generic `OTEL_EXPORTER_OTLP_ENDPOINT` set in managed settings governs every signal’s endpoint. If a lower-precedence source, such as user settings or a shell export, sets a signal-specific endpoint like `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`, Claude Code removes that variable at startup and logs a warning, visible with `claude --debug`. Users can’t point one signal’s OTLP traffic at a different endpoint, so you don’t need to set the signal-specific endpoint variables in managed settings to prevent it. This applies only on machines where an administrator deploys managed settings with telemetry configured, and it changes where telemetry is delivered, not what Claude Code collects. A managed `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_CLIENT_KEY`, or `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE` variable also governs the endpoint variables, since those credentials would otherwise accompany telemetry to a collector the managed settings didn’t choose. Two cases keep the normal per-key precedence: - - * Signal-specific variables set in the managed settings file itself still apply, so you can route one signal to a different collector by setting them there, as the SIEM example does. - * The exporter selectors (`OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and the beta `OTEL_TRACES_EXPORTER`) and the protocol variables follow per-key precedence, so a lower-precedence source can still change how a signal is exported. To make those authoritative too, set the signal-specific keys in managed settings directly. - -Before v2.1.217, every variable followed per-key settings precedence independently, so a signal-specific endpoint set in user settings or the shell redirected that signal away from the managed collector. +How managed settings lock the OTLP destination + +When you set an `OTEL_EXPORTER_OTLP_*` variable in managed settings, Claude Code removes conflicting developer-set variables at startup and logs a warning you can see with `claude --debug`. What it removes depends on which variable you set: + + * **Endpoints** : when you set `OTEL_EXPORTER_OTLP_ENDPOINT`, Claude Code removes every developer-set per-signal endpoint. Developers can’t point one signal at a different collector, so you don’t need to also set the per-signal endpoint variables in managed settings. + * **Protocols** : when you set `OTEL_EXPORTER_OTLP_PROTOCOL`, Claude Code removes every developer-set per-signal protocol. + * **Credentials** : when you set `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_CLIENT_KEY`, or `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`, Claude Code removes the developer-set per-signal versions of that variable, plus every developer-set endpoint variable, generic or per-signal, since those credentials would otherwise reach a collector the managed settings didn’t choose. + * **Exporter selectors** : `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and the beta `OTEL_TRACES_EXPORTER` follow normal per-key precedence. A developer’s setting can still disable a signal or switch it to the console exporter, so set the selectors in managed settings too if you need them locked. + +Claude Code doesn’t remove per-signal variables that you set in managed settings itself, so you can route one signal to a different collector by setting its variable there, as the SIEM example does. If you set a per-signal credential there, Claude Code removes the developer-set endpoint for that signal. This removal behavior changes where telemetry is delivered, not what Claude Code collects. Before v2.1.217, every variable followed per-key settings precedence independently, so a signal-specific endpoint set in user settings or the shell redirected that signal away from the managed collector. ## @@ -81,14 +83,14 @@ Common configuration variables -These variables configure exporters, endpoints, and export behavior for all deployments. A signal-specific variable overrides its generic counterpart, except that a generic endpoint or credential variable set in managed settings governs all signals’ endpoints and can’t be overridden from lower-precedence sources. +These variables configure exporters, endpoints, and export behavior for all deployments. A per-signal variable overrides its generic counterpart. On machines with managed settings, see How managed settings lock the OTLP destination for what Claude Code removes. Environment Variable| Description| Example Values ---|---|--- `CLAUDE_CODE_ENABLE_TELEMETRY`| Enables telemetry collection (required)| `1` `OTEL_METRICS_EXPORTER`| Metrics exporter types, comma-separated. Use `none` to disable| `console`, `otlp`, `prometheus`, `none` `OTEL_LOGS_EXPORTER`| Logs/events exporter types, comma-separated. Use `none` to disable| `console`, `otlp`, `none` -`OTEL_EXPORTER_OTLP_PROTOCOL`| Protocol for OTLP exporter, applies to all signals| `grpc`, `http/json`, `http/protobuf` +`OTEL_EXPORTER_OTLP_PROTOCOL`| Protocol for OTLP exporter, applies to all signals. Claude Code has no default protocol, so set this or the signal-specific protocol variable for each `otlp` exporter you enable| `grpc`, `http/json`, `http/protobuf` `OTEL_EXPORTER_OTLP_ENDPOINT`| OTLP collector endpoint for all signals| `http://localhost:4317` `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL`| Protocol for metrics, overrides general setting| `grpc`, `http/json`, `http/protobuf` `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`| OTLP metrics endpoint, overrides general setting| `http://localhost:4318/v1/metrics` @@ -121,7 +123,7 @@ `http/protobuf`, `http/json`| `CLAUDE_CODE_CLIENT_CERT`, `CLAUDE_CODE_CLIENT_KEY`, and optionally `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE`. See [Network configuration](</docs/en/network-config#mtls-authentication>)| `NODE_EXTRA_CA_CERTS` `grpc`| `OTEL_EXPORTER_OTLP_CLIENT_KEY` and `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`, or the per-signal variants such as `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` to use a different certificate per signal| `OTEL_EXPORTER_OTLP_CERTIFICATE` -For `grpc`, the OpenTelemetry SDK reads the standard OTLP variables directly, so existing configurations that set the per-signal metrics variables continue to work. +For `grpc`, the OpenTelemetry SDK reads the standard OTLP variables directly, so existing configurations that set the per-signal metrics variables continue to work. On machines with managed settings, Claude Code may remove developer-set per-signal credentials and endpoints at startup. ### @@ -147,7 +149,7 @@ Traces (beta) -Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend. Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the common OTLP configuration for endpoint, protocol, headers, and mTLS. A generic endpoint or credential variable set in managed settings governs the traces endpoint too, so the `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` override in the table below applies only when managed settings don’t set one. +Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend. Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the common OTLP configuration for endpoint, protocol, headers, and mTLS. On machines with managed settings, Claude Code may remove developer-set `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` and `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` variables at startup. Environment Variable| Description| Example Values ---|---|--- @@ -367,7 +369,7 @@ Example configurations -Set these environment variables before running `claude`. Each scenario below shows a complete configuration, and each variable is described under Common configuration variables. For console debugging with a 1-second export interval: +Set these environment variables before running `claude`. Each scenario below shows a complete configuration, and each variable is described under Common configuration variables. To confirm a configuration took effect, check your backend for the `claude_code.session.count` metric after starting a session; the Quick start covers logs-only verification and what to check when nothing arrives. For console debugging with a 1-second export interval: export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=console @@ -1265,6 +1267,8 @@ } } +To confirm events arrive, submit a prompt in a session running under this configuration and check your SIEM for the `claude_code.user_prompt` event. If nothing arrives, run `claude --debug` and check the debug log for OTel export errors. + ## ​
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -56,6 +56,19 @@ Claude Code doesn’t pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool doesn’t inherit Claude Code’s exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry. +### + +​ + +Managed endpoints govern signal-specific endpoints + +A generic `OTEL_EXPORTER_OTLP_ENDPOINT` set in managed settings governs every signal’s endpoint. If a lower-precedence source, such as user settings or a shell export, sets a signal-specific endpoint like `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`, Claude Code removes that variable at startup and logs a warning, visible with `claude --debug`. Users can’t point one signal’s OTLP traffic at a different endpoint, so you don’t need to set the signal-specific endpoint variables in managed settings to prevent it. This applies only on machines where an administrator deploys managed settings with telemetry configured, and it changes where telemetry is delivered, not what Claude Code collects. A managed `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_CLIENT_KEY`, or `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE` variable also governs the endpoint variables, since those credentials would otherwise accompany telemetry to a collector the managed settings didn’t choose. Two cases keep the normal per-key precedence: + + * Signal-specific variables set in the managed settings file itself still apply, so you can route one signal to a different collector by setting them there, as the SIEM example does. + * The exporter selectors (`OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and the beta `OTEL_TRACES_EXPORTER`) and the protocol variables follow per-key precedence, so a lower-precedence source can still change how a signal is exported. To make those authoritative too, set the signal-specific keys in managed settings directly. + +Before v2.1.217, every variable followed per-key settings precedence independently, so a signal-specific endpoint set in user settings or the shell redirected that signal away from the managed collector. + ## ​ @@ -67,6 +80,8 @@ ​ Common configuration variables + +These variables configure exporters, endpoints, and export behavior for all deployments. A signal-specific variable overrides its generic counterpart, except that a generic endpoint or credential variable set in managed settings governs all signals’ endpoints and can’t be overridden from lower-precedence sources. Environment Variable| Description| Example Values ---|---|--- @@ -132,7 +147,7 @@ Traces (beta) -Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend. Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the common OTLP configuration for endpoint, protocol, headers, and mTLS. +Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend. Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the common OTLP configuration for endpoint, protocol, headers, and mTLS. A generic endpoint or credential variable set in managed settings governs the traces endpoint too, so the `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` override in the table below applies only when managed settings don’t set one. Environment Variable| Description| Example Values ---|---|---
modified
Show diff (303 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -31,7 +31,7 @@ The default export intervals are 60 seconds for metrics and 5 seconds for logs. During setup, you may want to use shorter intervals for debugging purposes. Remember to reset these for production use. -For full configuration options, see the [OpenTelemetry specification](<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options>). +To verify a setup that exports metrics, check your backend for the `claude_code.session.count` metric, which Claude Code emits when a session starts. To verify a logs-only setup, submit a prompt and check for the `claude_code.user_prompt` event. If nothing arrives, run `claude --debug` and check the debug log for OTel export errors. For full configuration options, see the [OpenTelemetry specification](<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options>). ## @@ -84,9 +84,10 @@ `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable `OTEL_LOG_ASSISTANT_RESPONSES`| Enable logging of assistant response text on `assistant_response` events (default: disabled). When unset, falls back to the value of `OTEL_LOG_USER_PROMPTS`. Requires Claude Code v2.1.193 or later| `1` to enable, `0` to keep redacted -`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, user-authored workflow names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events (default: disabled)| `1` to enable -`OTEL_LOG_TOOL_CONTENT`| Enable logging of tool input and output content in span events (default: disabled). Requires tracing. Content is truncated at 60 KB| `1` to enable -`OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). 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| `1` for inline bodies truncated at 60 KB, or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event +`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, user-authored workflow names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events (default: disabled). For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `mcp_server_name`/`mcp_tool_name` emit on `tool_decision`/`tool_result` even with the flag off. The exception requires Claude Code v2.1.214 or later| `1` to enable +`OTEL_LOG_TOOL_CONTENT`| Enable logging of tool input and output content in span events (default: disabled). Requires tracing. Content is truncated at the content limit (60 KB by default)| `1` to enable +`OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). 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| `1` for inline bodies truncated at the content limit (60 KB by default), or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event +`CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH`| Content limit: the maximum length of content-bearing attributes such as model responses, tool content, system prompts, and raw API bodies, truncation marker included, in UTF-16 code units (default: 61440, i.e. 60 KB). The default is sized for backends that cap attribute values at 64 KB; raise it only if your backend accepts larger values, or lower it to cut telemetry volume. When an OpenTelemetry SDK attribute limit, `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` or one of its logrecord and span variants, is set lower, Claude Code truncates at that smaller value so the `[TRUNCATED ...]` marker stays within the SDK limit. Requires Claude Code v2.1.214 or later| `262144` `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes)| `900000` @@ -141,7 +142,7 @@ `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`| OTLP traces endpoint, overrides `OTEL_EXPORTER_OTLP_ENDPOINT`| `http://localhost:4318/v1/traces` `OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000` -Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. When tracing is active and Claude Code is connected directly to the Anthropic API, each model request carries a W3C `traceparent` header set to the `claude_code.llm_request` span’s context, and the API’s `traceresponse` header is recorded as a span link. Together these connect Claude Code’s client-side spans to the server-side trace through any compliant intermediary. Outbound HTTP MCP requests carry `traceparent` the same way. The header is not sent to third-party providers. By default, the `traceparent` header on model and HTTP MCP requests is sent only when `ANTHROPIC_BASE_URL` is unset or points at the Anthropic API, since some proxies reject unrecognized headers. The subprocess `TRACEPARENT` variable is controlled by the same switch for consistency. If you run Claude Code through a custom `ANTHROPIC_BASE_URL` proxy and want trace context propagated, set `CLAUDE_CODE_PROPAGATE_TRACEPARENT=1`. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. The inbound trace context also applies to events. In Agent SDK and `-p` sessions with `TRACEPARENT` set, each OTLP event log record carries `trace_id` and `span_id` values that join it to your application’s trace, even when the traces exporter isn’t configured, so your logging backend can correlate events with the rest of the trace. A record emitted inside an active Claude Code span carries that span’s ids; a record emitted outside one carries the inbound `TRACEPARENT` ids directly. Before v2.1.212, event records emitted outside an active span didn’t carry `trace_id` or `span_id`. +Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. When tracing is active and Claude Code is connected directly to the Anthropic API, each model request carries a W3C `traceparent` header set to the `claude_code.llm_request` span’s context, and the API’s `traceresponse` header is recorded as a span link. Together these connect Claude Code’s client-side spans to the server-side trace through any compliant intermediary. Outbound HTTP MCP requests carry `traceparent` the same way. The header is not sent to third-party providers. By default, the `traceparent` header on model and HTTP MCP requests is sent only when `ANTHROPIC_BASE_URL` is unset or points at the Anthropic API, since some proxies reject unrecognized headers. The subprocess `TRACEPARENT` variable is controlled by the same switch for consistency. If you run Claude Code through a custom `ANTHROPIC_BASE_URL` proxy and want trace context propagated, set `CLAUDE_CODE_PROPAGATE_TRACEPARENT=1`. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. The inbound trace context also applies to events. In Agent SDK and `-p` sessions with `TRACEPARENT` set, each OTLP event log record carries `trace_id` and `span_id` values that join it to your application’s trace, even when the traces exporter isn’t configured, so your logging backend can correlate events with the rest of the trace. A record emitted while an interaction is active carries the interaction span’s IDs, even when Claude Code emits it outside the span’s async context, such as in a permission prompt callback or for a record buffered during startup and exported later. A record emitted with no active interaction span carries the inbound `TRACEPARENT` IDs directly. Before v2.1.214, records emitted outside the span’s async context carried the inbound `TRACEPARENT` IDs instead of the span’s IDs. Before v2.1.212, event records emitted outside an active span didn’t carry `trace_id` or `span_id`. #### @@ -225,7 +226,7 @@ `skill_name`| Skill name for the Skill tool| `OTEL_LOG_TOOL_DETAILS` `subagent_type`| Subagent type for the Agent tool or legacy Task tool| `OTEL_LOG_TOOL_DETAILS` -When `OTEL_LOG_TOOL_CONTENT=1`, this span also records a `tool.output` span event whose attributes contain the tool’s input and output bodies, truncated at 60 KB per attribute. **`claude_code.tool.blocked_on_user`** +When `OTEL_LOG_TOOL_CONTENT=1`, this span also records a `tool.output` span event whose attributes contain the tool’s input and output bodies, truncated at the content limit (60 KB by default) per attribute. **`claude_code.tool.blocked_on_user`** Attribute| Description| Gated by ---|---|--- @@ -257,7 +258,7 @@ `num_non_blocking_error`| Count of hooks that failed without blocking| `num_cancelled`| Count of hooks cancelled before completion| -Additional content-bearing attributes such as `new_context`, `system_prompt_preview`, `user_system_prompt`, `tool_input`, and `response.model_output` are emitted only when detailed beta tracing is active. They are not part of the stable span schema. `user_system_prompt` additionally requires `OTEL_LOG_USER_PROMPTS=1`. It carries only the system prompt text you provide via the `systemPrompt` SDK option or `--system-prompt` and `--append-system-prompt` flags, truncated at 60 KB, and is emitted once per session rather than per request. +Additional content-bearing attributes such as `new_context`, `system_prompt_preview`, `user_system_prompt`, `tool_input`, and `response.model_output` are emitted only when detailed beta tracing is active. They are not part of the stable span schema.`user_system_prompt` additionally requires `OTEL_LOG_USER_PROMPTS=1`. It carries only the system prompt text you provide via the `systemPrompt` SDK option or `--system-prompt` and `--append-system-prompt` flags, truncated at the content limit (60 KB by default), and is emitted once per session rather than per request. ### @@ -273,10 +274,10 @@ Settings configuration -Add to your `.claude/settings.json`: +Add to your `.claude/settings.json`, replacing the path with your own script: { - "otelHeadersHelper": "/bin/generate_opentelemetry_headers.sh" + "otelHeadersHelper": "/path/to/generate-otel-headers.sh" } The value can be the path to an executable file, including a path that contains spaces, or a shell command line with arguments. On Windows, the value always runs through the shell, so quote a path that contains spaces inside the JSON value. @@ -351,29 +352,32 @@ Example configurations -Set these environment variables before running `claude`. Each block shows a complete configuration for a different exporter or deployment scenario: - - # Console debugging (1-second intervals) +Set these environment variables before running `claude`. Each scenario below shows a complete configuration, and each variable is described under Common configuration variables. For console debugging with a 1-second export interval: + export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=console export OTEL_METRIC_EXPORT_INTERVAL=1000 - # OTLP/gRPC +For OTLP over gRPC: + export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=otlp export OTEL_EXPORTER_OTLP_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 - # Prometheus +For Prometheus, scraped from `http://localhost:9464/metrics`: + export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=prometheus - # Multiple exporters +To send metrics to multiple exporters: + export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=console,otlp export OTEL_EXPORTER_OTLP_PROTOCOL=http/json - # Different endpoints/backends for metrics and logs +To send metrics and logs to different endpoints or backends: + export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=otlp export OTEL_LOGS_EXPORTER=otlp @@ -382,13 +386,15 @@ export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://logs.example.com:4317 - # Metrics only (no events/logs) +To export metrics only, without events or logs: + export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=otlp export OTEL_EXPORTER_OTLP_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 - # Events/logs only (no metrics) +To export events and logs only, without metrics: + export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_LOGS_EXPORTER=otlp export OTEL_EXPORTER_OTLP_PROTOCOL=grpc @@ -434,18 +440,20 @@ Metrics -Claude Code exports the following metrics: +Claude Code exports the following metrics. The Unit column shows the OpenTelemetry unit string attached to each metric; count metrics carry none. Metric Name| Description| Unit ---|---|--- -`claude_code.session.count`| Count of CLI sessions started| count -`claude_code.lines_of_code.count`| Count of lines of code modified| count -`claude_code.pull_request.count`| Number of pull requests created| count -`claude_code.commit.count`| Number of git commits created| count +`claude_code.session.count`| Count of CLI sessions started| none +`claude_code.lines_of_code.count`| Count of lines of code modified| none +`claude_code.pull_request.count`| Number of pull requests created| none +`claude_code.commit.count`| Number of git commits created| none `claude_code.cost.usage`| Cost of the Claude Code session| USD `claude_code.token.usage`| Number of tokens used| tokens -`claude_code.code_edit_tool.decision`| Count of code editing tool permission decisions| count -`claude_code.active_time.total`| Total active time in seconds| s +`claude_code.code_edit_tool.decision`| Count of code editing tool permission decisions| none +`claude_code.active_time.total`| Total active time| s + +When `prometheus` is the only exporter listed in `OTEL_METRICS_EXPORTER`, Claude Code omits the `USD`, `tokens`, and `s` units from the exported metrics so the scrape stays valid Prometheus text format. Metric names don’t change, and configurations that combine exporters, such as `otlp,prometheus`, keep the units. Before v2.1.216, the Prometheus scrape included OpenMetrics-only `# UNIT` lines that some scrapers rejected. ### @@ -578,8 +586,14 @@ Attribute| Description ---|--- `prompt.id`| UUID v4 identifier linking all events produced while processing a single user prompt - -To trace all activity triggered by a single prompt, filter your events by a specific `prompt.id` value. This returns the user_prompt event, any api_request events, and any tool_result events that occurred while processing that prompt. +`message.uuid`| UUID of the message as persisted in the session transcript, the `~/.claude/projects/*/*.jsonl` files. Present on `assistant_response`, and on `user_prompt` except for command dispatches, which can produce zero or many messages. On `assistant_response`, this is the response’s final transcript entry, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.214 or later +`client_request_id`| Client-generated UUID sent as the `x-client-request-id` request header. Present on `api_request` and `api_error` on first-party API connections; absent on third-party provider backends and when the request was retried through the non-streaming fallback. Pairs a request with its response and remains available for failures such as timeouts that never produced a server `request_id`. Matches the same attribute on the `llm_request` trace span. Requires Claude Code v2.1.214 or later + +To trace all activity triggered by a single prompt, filter your events by a specific `prompt.id` value. This returns the user_prompt event, any api_request events, and any tool_result events that occurred while processing that prompt. For message-level reconstruction, each event class carries a key that matches a field in the session transcript. The transcript entry format is [internal to Claude Code](</docs/en/sessions#where-transcripts-are-stored>) and changes between versions, so a pipeline that joins on these fields can break on any release; treat the joins as version-specific rather than a stable contract: + + * `message.uuid` on `user_prompt` and `assistant_response` + * `request_id` on the API events, persisted as `requestId` on the transcript’s assistant entries + * `tool_use_id` on `tool_result` and `tool_decision` events `prompt.id` is intentionally excluded from metrics because each prompt generates a unique ID, which would create an ever-growing number of time series. Use it for event-level analysis and audit trails only. @@ -597,6 +611,7 @@ * `event.sequence`: monotonically increasing counter for ordering events within a session * `prompt_length`: Length of the prompt * `prompt`: Prompt content. Redacted by default. Set `OTEL_LOG_USER_PROMPTS=1` to include it + * `message.uuid`: UUID of the resulting user message, matching the persisted transcript entry. Absent on command dispatches, which can produce zero or many messages. Requires Claude Code v2.1.214 or later * `command_name`: Command name when the prompt invokes one. Built-in and bundled command names such as `compact` or `debug` are emitted as-is; aliases such as `reset` emit as typed rather than the canonical name. Custom, plugin, and MCP command names collapse to `custom` or `mcp` unless `OTEL_LOG_TOOL_DETAILS=1` is set * `command_source`: Origin of the command when present: `builtin`, `custom`, or `mcp`. Plugin-provided commands report as `custom` @@ -613,9 +628,10 @@ * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session * `response_length`: Length of the response text in characters - * `response`: Response text, truncated at 60 KB. Redacted to `<REDACTED>` by default. Set `OTEL_LOG_ASSISTANT_RESPONSES=1` to include it. When `OTEL_LOG_ASSISTANT_RESPONSES` is unset, `OTEL_LOG_USER_PROMPTS` controls it instead, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` to keep responses redacted while prompt logging is on + * `response`: Response text, truncated at the content limit (60 KB by default). Redacted to `<REDACTED>` by default. Set `OTEL_LOG_ASSISTANT_RESPONSES=1` to include it. When `OTEL_LOG_ASSISTANT_RESPONSES` is unset, `OTEL_LOG_USER_PROMPTS` controls it instead, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` to keep responses redacted while prompt logging is on * `model`: Model identifier (for example, “claude-sonnet-5”) * `request_id`: Anthropic API request ID from the response’s `request-id` header. Present only when the API returns one + * `message.uuid`: UUID of the response’s final transcript entry. An API response is persisted as one transcript entry per content block; this is the last one, which the next turn’s `parentUuid` chains from. Requires Claude Code v2.1.214 or later * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name #### @@ -641,9 +657,8 @@ * `tool_input_size_bytes`: Size of the JSON-serialized tool input in bytes * `tool_result_size_bytes`: Size of the tool result in bytes * `mcp_server_scope`: MCP server scope identifier (for MCP tools) - * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters: - * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds) - * For WorkspaceBash tool: includes `bash_command`, `full_command`, `timeout` + * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, the `mcp_server_name`/`mcp_tool_name` pair is included even with the flag off, the same host-authored exception as the Tool decision event, requiring Claude Code v2.1.214 or later. The parameters vary by tool: + * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds). The desktop app’s workspace bash tool also reports `tool_name` as `Bash`, but includes only `bash_command`, `full_command`, and `timeout` * For MCP tools: includes `mcp_server_name`, `mcp_tool_name` * For Skill tool: includes `skill_name` * For Agent tool or legacy Task tool: includes `subagent_type` @@ -663,12 +678,14 @@ * `event.sequence`: monotonically increasing counter for ordering events within a session * `model`: Model used (for example, “claude-sonnet-5”) * `cost_usd`: Estimated cost in USD + * `cost_usd_micros`: Estimated cost in millionths of a US dollar, emitted as an integer * `duration_ms`: Request duration in milliseconds * `input_tokens`: Number of input tokens * `output_tokens`: Number of output tokens * `cache_read_tokens`: Number of tokens read from cache * `cache_creation_tokens`: Number of tokens used for cache creation * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. + * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header. Matches the same attribute on the `llm_request` trace span. Absent on third-party provider backends and when the request was retried through the non-streaming fallback. Requires Claude Code v2.1.214 or later * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model doesn’t support effort. @@ -692,6 +709,7 @@ * `duration_ms`: Request duration in milliseconds * `attempt`: Total number of attempts made, including the initial request (`1` means no retries occurred) * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. + * `client_request_id`: Client-generated UUID sent as the `x-client-request-id` request header. Available even when a failure such as a timeout or connection error never produced a server `request_id`. Absent on third-party provider backends and when the request was retried through the non-streaming fallback. Requires Claude Code v2.1.214 or later * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when the model doesn’t support effort. @@ -733,7 +751,7 @@ * `event.name`: `"api_request_body"` * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session - * `body`: JSON-serialized Messages API request parameters (system prompt, messages, tools, etc.), truncated at 60 KB. Extended-thinking content in prior assistant turns is redacted. Emitted only in inline mode (`OTEL_LOG_RAW_API_BODIES=1`). + * `body`: JSON-serialized Messages API request parameters, such as the system prompt, messages, and tools, truncated at the content limit (60 KB by default). Extended-thinking content in prior assistant turns is redacted. Emitted only in inline mode (`OTEL_LOG_RAW_API_BODIES=1`). * `body_ref`: Absolute path to a `<dir>/<uuid>.request.json` file containing the untruncated body. Emitted only in file mode (`OTEL_LOG_RAW_API_BODIES=file:<dir>`). * `body_length`: Untruncated body length. UTF-8 bytes when `OTEL_LOG_RAW_API_BODIES=file:<dir>`, or UTF-16 code units when `=1` * `body_truncated`: `"true"` when inline truncation occurred. Absent in file mode and when no truncation occurred. @@ -752,7 +770,7 @@ * `event.name`: `"api_response_body"` * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session - * `body`: JSON-serialized Messages API response (id, content blocks, usage, stop reason), truncated at 60 KB. Extended-thinking content is redacted. Emitted only in inline mode (`OTEL_LOG_RAW_API_BODIES=1`). + * `body`: JSON-serialized Messages API response, including the id, content blocks, usage, and stop reason, truncated at the content limit (60 KB by default). Extended-thinking content is redacted. Emitted only in inline mode (`OTEL_LOG_RAW_API_BODIES=1`). * `body_ref`: Absolute path to a `<dir>/<request_id>.response.json` file containing the untruncated body. Emitted only in file mode (`OTEL_LOG_RAW_API_BODIES=file:<dir>`). * `body_length`: Untruncated body length. UTF-8 bytes when `OTEL_LOG_RAW_API_BODIES=file:<dir>`, or UTF-16 code units when `=1` * `body_truncated`: `"true"` when inline truncation occurred. Absent in file mode and when no truncation occurred. @@ -775,16 +793,20 @@ * `tool_name`: Name of the tool (for example, “Read”, “Edit”, “Write”, “NotebookEdit”) * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. * `decision`: Either `"accept"` or `"reject"` + * `tool_source`: Always present. The tool’s provenance, as a closed set of CLI-authored values. Requires Claude Code v2.1.214 or later + * `"builtin"`: the CLI’s own tools + * `"mcp"`: MCP servers generally + * `"sdk_host_builtin_mcp"`: an in-process server built into Claude Desktop itself, in a session Claude Desktop owns. Claude Desktop owns a session it started from one of its own entrypoints, `claude-desktop`, `claude-desktop-3p`, or `local-agent`, when that session isn’t a nested child; nested sessions, including sessions Claude Code itself spawns, report these servers as `"mcp"` * `source`: Where the decision came from: - * `"config"`: Decided automatically without prompting, based on project settings, allow or deny rules in the user’s personal settings, enterprise managed policy, `--allowedTools` or `--disallowedTools` flags, the active permission mode, a session-scoped grant from an earlier prompt in the same interactive CLI session, or because the tool is inherently safe. The event doesn’t indicate which of these sources matched. + * `"config"`: Decided automatically without prompting, based on project settings, allow or deny rules in the user’s personal settings, enterprise managed policy, `--allowedTools` or `--disallowedTools` flags, the active permission mode, a session-scoped grant from an earlier prompt in the same interactive CLI session, or because the tool is inherently safe. The event doesn’t indicate which of these sources matched. Claude Code also reports `"config"` when the permission prompt request itself fails, for example when the Agent SDK’s [`canUseTool`](</docs/en/agent-sdk/typescript#canusetool>) callback or the [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) tool returns an invalid result, or when the input stream closes while the request is pending. Before v2.1.216, Claude Code reported these failures as `"user_reject"`. * `"hook"`: A `PreToolUse` or `PermissionRequest` hook returned the decision. * `"user_permanent"`: Emitted when the user chose “Yes, and don’t ask again for …” at a permission prompt, which saves an allow rule to their personal settings. In the interactive CLI this is emitted only for that choice itself; later calls that match the saved rule emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the initial choice and later rule matches emit `"user_permanent"`. Treated as an accept. * `"user_temporary"`: Emitted when the user chose “Yes” at a permission prompt for a one-time approval, or chose one of the ”… during this session” options on a file edit or read prompt. In the interactive CLI this is emitted only for the choice itself; later calls allowed by that session-scoped grant emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the choice and later matches emit `"user_temporary"`. Treated as an accept. - * `"user_abort"`: Emitted when the user dismissed the permission prompt without answering. Treated as a reject. + * `"user_abort"`: Emitted when the user dismissed the permission prompt without answering. In Agent SDK and non-interactive `-p` sessions, this includes interrupting the turn while a `canUseTool` or `--permission-prompt-tool` permission request is pending; before v2.1.216, Claude Code reported that interrupt as `"user_reject"`. Treated as a reject. * `"user_reject"`: Emitted when the user chose “No” when prompted. In the interactive CLI this is emitted only for that choice itself; calls that match a deny rule in the user’s personal settings emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, calls that match a deny rule in personal settings emit `"user_reject"`. Treated as a reject. * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters. Same shape as the Tool result event, minus post-execution fields such as `git_commit_id`. Values may differ from `tool_result` for an accepted call if the permission decision rewrites the tool input via `updatedInput`. Use this attribute to see which command was rejected when `decision` is `"reject"`. - * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox` - * For WorkspaceBash tool: includes `bash_command`, `full_command`, `timeout` + * For `"sdk_host_builtin_mcp"` tools: `mcp_server_name` and `mcp_tool_name` are included even when `OTEL_LOG_TOOL_DETAILS` is off, because the host application defines these names; without them, a rejected call to one of these built-in servers would be unattributable on the default stream. For user-configured MCP servers, the event’s `tool_name` is always the literal `"mcp_tool"`, and the server and tool names appear only in `tool_parameters` with the flag on; argument content requires the flag everywhere. Requires Claude Code v2.1.214 or later + * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`. The desktop app’s workspace bash tool also reports `tool_name` as `Bash`, but includes only `bash_command`, `full_command`, and `timeout` * For MCP tools: includes `mcp_server_name`, `mcp_tool_name` * For Skill tool: includes `skill_name` * For Agent tool or legacy Task tool: includes `subagent_type` @@ -1112,6 +1134,8 @@ Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, Amazon Bedrock, or Google Cloud’s Agent Platform). +Claude Code counts each streaming response toward the cost and token metrics exactly once, including when a gateway or proxy behind `ANTHROPIC_BASE_URL` streams usage progressively across multiple frames. Before v2.1.214, streams that carried usage in more than one frame inflated `claude_code.cost.usage` and `claude_code.token.usage` by roughly one extra full request per extra frame. + ### ​ @@ -1183,8 +1207,8 @@ Without `OTEL_LOG_TOOL_DETAILS`, these events drop the identifying detail: - * `tool_result`: keeps `tool_name` and `mcp_server_scope`, omits `mcp_server_name`, `mcp_tool_name`, and arguments - * `tool_decision`: keeps `tool_name`, omits `tool_parameters` + * `tool_result`: keeps `mcp_server_scope` and a `tool_name` redacted to the literal `"mcp_tool"` for user-configured servers, omits argument content. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, it also keeps the `mcp_server_name`/`mcp_tool_name` pair inside `tool_parameters`, the same host-authored exception as `tool_decision`, requiring Claude Code v2.1.214 or later + * `tool_decision`: keeps `tool_source` and a `tool_name` redacted to the literal `"mcp_tool"` for user-configured servers, omits argument content. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, it also keeps the `mcp_server_name`/`mcp_tool_name` pair inside `tool_parameters`; `tool_source` and the name pair both require Claude Code v2.1.214 or later * `mcp_server_connection`: omits `server_name` and the error message, but keeps `is_plugin`, `plugin_id_hash`, and `plugin.name`, with non-Anthropic plugin names redacted to the literal `"third-party"`, so plugin-provided servers remain distinguishable without detailed logging ### @@ -1304,13 +1328,13 @@ * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` * Assistant response text is not collected by default. Only response length is recorded. To include response text, set `OTEL_LOG_ASSISTANT_RESPONSES=1`. Like all OpenTelemetry data from Claude Code, the response text is sent only to the OTel endpoint you configure, never to Anthropic. When this variable is unset, `OTEL_LOG_USER_PROMPTS` is used as a fallback, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` if you want prompt content without response content - * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. This data is sent only to the OTEL endpoint you configure, never to Anthropic. Arguments may still contain sensitive values, so configure your telemetry backend to filter or redact these attributes as needed. When enabled: + * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, `tool_decision` and `tool_result` carry the `mcp_server_name`/`mcp_tool_name` pair, host-authored names rather than argument content, even with the flag off. The exception requires Claude Code v2.1.214 or later. This data is sent only to the OTEL endpoint you configure, never to Anthropic. Arguments may still contain sensitive values, so configure your telemetry backend to filter or redact these attributes as needed. When enabled: * `tool_result` and `tool_decision` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names. Fields such as `full_command` are emitted untruncated * `tool_result` events additionally include a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters * `user_prompt` events include the verbatim `command_name` for custom, plugin, and MCP commands * Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`, with the same truncation as `tool_input` - * Tool input and output content is not logged in trace spans by default. To include it, set `OTEL_LOG_TOOL_CONTENT=1`. When enabled, span events include full tool input and output content truncated at 60 KB per span. This can include raw file contents from Read tool results and Bash command output. Configure your telemetry backend to filter or redact these attributes as needed - * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES`. With `=1`, each API call emits `api_request_body` and `api_response_body` log events whose `body` attribute is the JSON-serialized payload, truncated at 60 KB. With `=file:<dir>`, untruncated bodies are written to `.request.json` and `.response.json` files under that directory and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. In both modes, bodies contain the full conversation history (system prompt, every prior user and assistant turn, tool results), so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude’s extended-thinking content is always redacted from these bodies regardless of other settings + * Tool input and output content is not logged in trace spans by default. To include it, set `OTEL_LOG_TOOL_CONTENT=1`. When enabled, span events include full tool input and output content truncated at the content limit (60 KB by default) per attribute. This can include raw file contents from Read tool results and Bash command output. Configure your telemetry backend to filter or redact these attributes as needed + * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES`. With `=1`, each API call emits `api_request_body` and `api_response_body` log events whose `body` attribute is the JSON-serialized payload, truncated at the content limit (60 KB by default). With `=file:<dir>`, untruncated bodies are written to `.request.json` and `.response.json` files under that directory and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. In both modes, bodies contain the full conversation history, including the system prompt, every prior user and assistant turn, and tool results, so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude’s extended-thinking content is always redacted from these bodies regardless of other settings ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1275,13 +1275,15 @@ All metrics and events are exported with the following resource attributes: - * `service.name`: `claude-code` - * `service.version`: Current Claude Code version + * `service.name`: `claude-code` for terminal sessions, `claude-code-desktop` for sessions started from the Code tab in the [Claude Desktop app](</docs/en/desktop>) + * `service.version`: Current Claude Code version, or the Desktop app version for Code tab sessions * `os.type`: Operating system type (for example, `linux`, `darwin`, `windows`) * `os.version`: Operating system version string * `host.arch`: Host architecture (for example, `amd64`, `arm64`) * `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux) * Meter Name: `com.anthropic.claude_code` + +If your collector pipelines or dashboards filter on `service.name = claude-code`, add `claude-code-desktop` to the filter to also capture telemetry from Code tab sessions. ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -90,6 +90,8 @@ `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes)| `900000` +For the `http/protobuf` and `http/json` protocols, Claude Code sends each export request with a `Content-Length` header. Before v2.1.212, Claude Code versions from v2.1.191 onward sent these requests with chunked transfer encoding; Azure Monitor and other endpoints that require a declared length rejected them with `411 Length Required` or `400` errors. + ### ​ @@ -139,7 +141,7 @@ `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`| OTLP traces endpoint, overrides `OTEL_EXPORTER_OTLP_ENDPOINT`| `http://localhost:4318/v1/traces` `OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000` -Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. When tracing is active and Claude Code is connected directly to the Anthropic API, each model request carries a W3C `traceparent` header set to the `claude_code.llm_request` span’s context, and the API’s `traceresponse` header is recorded as a span link. Together these connect Claude Code’s client-side spans to the server-side trace through any compliant intermediary. Outbound HTTP MCP requests carry `traceparent` the same way. The header is not sent to third-party providers. By default, the `traceparent` header on model and HTTP MCP requests is sent only when `ANTHROPIC_BASE_URL` is unset or points at the Anthropic API, since some proxies reject unrecognized headers. The subprocess `TRACEPARENT` variable is controlled by the same switch for consistency. If you run Claude Code through a custom `ANTHROPIC_BASE_URL` proxy and want trace context propagated, set `CLAUDE_CODE_PROPAGATE_TRACEPARENT=1`. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. +Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. When tracing is active and Claude Code is connected directly to the Anthropic API, each model request carries a W3C `traceparent` header set to the `claude_code.llm_request` span’s context, and the API’s `traceresponse` header is recorded as a span link. Together these connect Claude Code’s client-side spans to the server-side trace through any compliant intermediary. Outbound HTTP MCP requests carry `traceparent` the same way. The header is not sent to third-party providers. By default, the `traceparent` header on model and HTTP MCP requests is sent only when `ANTHROPIC_BASE_URL` is unset or points at the Anthropic API, since some proxies reject unrecognized headers. The subprocess `TRACEPARENT` variable is controlled by the same switch for consistency. If you run Claude Code through a custom `ANTHROPIC_BASE_URL` proxy and want trace context propagated, set `CLAUDE_CODE_PROPAGATE_TRACEPARENT=1`. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. The inbound trace context also applies to events. In Agent SDK and `-p` sessions with `TRACEPARENT` set, each OTLP event log record carries `trace_id` and `span_id` values that join it to your application’s trace, even when the traces exporter isn’t configured, so your logging backend can correlate events with the rest of the trace. A record emitted inside an active Claude Code span carries that span’s ids; a record emitted outside one carries the inbound `TRACEPARENT` ids directly. Before v2.1.212, event records emitted outside an active span didn’t carry `trace_id` or `span_id`. ####
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -293,7 +293,7 @@ If the helper fails or prints output that doesn’t meet these requirements, Claude Code reports the error in: - * `/doctor` output + * `/status` output * The debug log, when running with [`--debug`](</docs/en/cli-reference#cli-flags>) or after running `/debug` in the session * stderr, in non-interactive sessions started with `-p`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -84,7 +84,7 @@ `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable `OTEL_LOG_ASSISTANT_RESPONSES`| Enable logging of assistant response text on `assistant_response` events (default: disabled). When unset, falls back to the value of `OTEL_LOG_USER_PROMPTS`. Requires Claude Code v2.1.193 or later| `1` to enable, `0` to keep redacted -`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events (default: disabled)| `1` to enable +`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, user-authored workflow names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events (default: disabled)| `1` to enable `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool input and output content in span events (default: disabled). Requires tracing. Content is truncated at 60 KB| `1` to enable `OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). 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| `1` for inline bodies truncated at 60 KB, or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` @@ -184,6 +184,8 @@ `query_source`| Subsystem that issued the request, such as `repl_main_thread` or a subagent name| `agent_id`| Identifier of the subagent or teammate that issued the request. Absent on the main session| `parent_agent_id`| Identifier of the agent that spawned this one. Absent for the main session and for agents spawned directly from it| +`workflow.run_id`| Run identifier of the [Workflow](</docs/en/workflows>) tool run that spawned this agent, prefixed `wf_`. Absent for agents not spawned by a workflow| +`workflow.name`| Name of the workflow that spawned this agent. User-authored names are replaced with `custom` unless the gate is set| `OTEL_LOG_TOOL_DETAILS` `speed`| `fast` or `normal`| `llm_request.context`| `interaction`, `tool`, or `standalone` depending on the parent span| `duration_ms`| Wall-clock duration including retries| @@ -212,6 +214,8 @@ `result_tokens`| Approximate token size of the tool result| `agent_id`| Identifier of the subagent or teammate that ran the tool. Absent on the main session| `parent_agent_id`| Identifier of the agent that spawned this one. Absent for the main session and for agents spawned directly from it| +`workflow.run_id`| Run identifier of the Workflow tool run that spawned this agent, prefixed `wf_`. Absent for agents not spawned by a workflow| +`workflow.name`| Name of the workflow that spawned this agent. User-authored names are replaced with `custom` unless the gate is set| `OTEL_LOG_TOOL_DETAILS` `tool_use_id`| The model’s `tool_use` block id for this call. Matches the `tool_use_id` on the tool_result and tool_decision events and in hook payloads, so you can join the span to those records| `gen_ai.tool.call.id`| Same value as `tool_use_id`. OpenTelemetry GenAI semantic convention| `file_path`| Target file path for Read, Edit, and Write tools| `OTEL_LOG_TOOL_DETAILS` @@ -419,6 +423,8 @@ * `prompt.id`: UUID correlating a user prompt with all subsequent events until the next prompt. See Event correlation attributes. * `workspace.host_paths`: host workspace directories selected in the desktop app, as a string array + * `workflow.run_id`: run identifier, prefixed `wf_`, on the API and tool events emitted by agents that belong to a [Workflow](</docs/en/workflows>) tool run. Filtering events by one `workflow.run_id` reconstructs that run’s API requests and tool results. The identifier covers the agents the workflow script spawns and any agents those spawn in turn, such as skill invocations. It matches the run identifier reported in the Workflow tool result. Absent on all other events. Requires Claude Code v2.1.202 or later + * `workflow.name`: name of the workflow, its script’s `meta.name`, emitted alongside `workflow.run_id`. Built-in workflow names appear verbatim when the run executes the unmodified built-in script. User-authored names, including edited copies of built-in scripts, are replaced with `custom` unless `OTEL_LOG_TOOL_DETAILS=1` is set. Requires Claude Code v2.1.202 or later ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -844,7 +844,7 @@ Internal error event -Logged when Claude Code catches an unexpected internal error. Only the error class name and an errno-style code are recorded. The error message and stack trace are never included. This event is not emitted when running against Bedrock, Vertex, or Foundry, or when `DISABLE_ERROR_REPORTING` is set. **Event Name** : `claude_code.internal_error` **Attributes** : +Logged when Claude Code catches an unexpected internal error. Only the error class name and an errno-style code are recorded. The error message and stack trace are never included. This event is not emitted when running against Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, or when `DISABLE_ERROR_REPORTING` is set. **Event Name** : `claude_code.internal_error` **Attributes** : * All standard attributes * `event.name`: `"internal_error"` @@ -1102,7 +1102,7 @@ * Identifying high-usage sessions for optimization * Attributing spend to specific skills, plugins, or subagent types via the `skill.name`, `plugin.name`, and `agent.name` attributes -Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, Amazon Bedrock, or Google Cloud Vertex). +Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, Amazon Bedrock, or Google Cloud’s Agent Platform). ### @@ -1155,7 +1155,7 @@ Attribute actions to users -The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account, plus `user.id` and the per-session `session.id`. `user.id` is an installation-scoped identifier, except on [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, where it is the IdP subject from the gateway-issued token. MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code doesn’t act under a separate service account; the identity recorded on each event is the developer’s own Claude account, or the developer’s IdP identity on a [Claude apps gateway](</docs/en/claude-apps-gateway>) session. When Claude Code authenticates with a direct API key, or against Bedrock, Vertex AI, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper. Claude apps gateway sessions need none of this: the CLI stamps the IdP identity automatically, as described in Standard attributes. +The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account, plus `user.id` and the per-session `session.id`. `user.id` is an installation-scoped identifier, except on [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, where it is the IdP subject from the gateway-issued token. MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code doesn’t act under a separate service account; the identity recorded on each event is the developer’s own Claude account, or the developer’s IdP identity on a [Claude apps gateway](</docs/en/claude-apps-gateway>) session. When Claude Code authenticates with a direct API key, or against Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper. Claude apps gateway sessions need none of this: the CLI stamps the IdP identity automatically, as described in Standard attributes. export OTEL_RESOURCE_ATTRIBUTES="enduser.id=jdoe@example.com,enduser.directory_id=S-1-5-21-..." @@ -1308,4 +1308,4 @@ Monitor Claude Code on Amazon Bedrock -For detailed Claude Code usage monitoring guidance for Amazon Bedrock, see [Claude Code Monitoring Implementation (Bedrock)](<https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md>). +For detailed Claude Code usage monitoring guidance for Amazon Bedrock, see [Claude Code Monitoring Implementation (Amazon Bedrock)](<https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md>).
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1124,7 +1124,7 @@ Detect retry exhaustion -Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records how many attempts were made in total. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15. When the request exhausts all retries on a transient error, `attempt` equals one more than that effective limit: 11 by default, and never more than 16. A lower value indicates a non-retryable error such as a `400` response. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. +Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records the total number of attempts. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15; as of v2.1.199, `CLAUDE_CODE_RETRY_WATCHDOG` raises the default and removes the cap. When the request exhausts all retries on a transient error, `attempt` equals one more than that effective limit: 11 by default, and never more than 16 unless the watchdog is set. A lower value indicates a non-retryable error such as a `400` response. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -606,7 +606,7 @@ * `event.sequence`: monotonically increasing counter for ordering events within a session * `response_length`: Length of the response text in characters * `response`: Response text, truncated at 60 KB. Redacted to `<REDACTED>` by default. Set `OTEL_LOG_ASSISTANT_RESPONSES=1` to include it. When `OTEL_LOG_ASSISTANT_RESPONSES` is unset, `OTEL_LOG_USER_PROMPTS` controls it instead, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` to keep responses redacted while prompt logging is on - * `model`: Model identifier (for example, “claude-sonnet-4-6”) + * `model`: Model identifier (for example, “claude-sonnet-5”) * `request_id`: Anthropic API request ID from the response’s `request-id` header. Present only when the API returns one * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -468,7 +468,7 @@ * All standard attributes * `type`: (`"added"`, `"removed"`) - * `model`: Model identifier for the model that made the change (for example, “claude-sonnet-4-6”). Requires Claude Code v2.1.172 or later + * `model`: Model identifier for the model that made the change (for example, “claude-sonnet-5”) #### @@ -499,7 +499,7 @@ Incremented after each API request. **Attributes** : * All standard attributes - * `model`: Model identifier (for example, “claude-sonnet-4-6”) + * `model`: Model identifier (for example, “claude-sonnet-5”) * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model doesn’t support effort. @@ -520,7 +520,7 @@ * All standard attributes * `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`) - * `model`: Model identifier (for example, “claude-sonnet-4-6”) + * `model`: Model identifier (for example, “claude-sonnet-5”) * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. See Cost counter for details. @@ -653,7 +653,7 @@ * `event.name`: `"api_request"` * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session - * `model`: Model used (for example, “claude-sonnet-4-6”) + * `model`: Model used (for example, “claude-sonnet-5”) * `cost_usd`: Estimated cost in USD * `duration_ms`: Request duration in milliseconds * `input_tokens`: Number of input tokens @@ -678,7 +678,7 @@ * `event.name`: `"api_error"` * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session - * `model`: Model used (for example, “claude-sonnet-4-6”) + * `model`: Model used (for example, “claude-sonnet-5”) * `error`: Error message * `status_code`: HTTP status code as a number. Absent for non-HTTP errors such as connection failures. * `duration_ms`: Request duration in milliseconds
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -83,6 +83,7 @@ `OTEL_METRIC_EXPORT_INTERVAL`| Export interval in milliseconds (default: 60000)| `5000`, `60000` `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable +`OTEL_LOG_ASSISTANT_RESPONSES`| Enable logging of assistant response text on `assistant_response` events (default: disabled). When unset, falls back to the value of `OTEL_LOG_USER_PROMPTS`. Requires Claude Code v2.1.193 or later| `1` to enable, `0` to keep redacted `OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events (default: disabled)| `1` to enable `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool input and output content in span events (default: disabled). Requires tracing. Content is truncated at 60 KB| `1` to enable `OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). 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| `1` for inline bodies truncated at 60 KB, or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event @@ -414,7 +415,7 @@ `terminal.type`| Terminal type, such as `iTerm.app`, `vscode`, `cursor`, or `tmux`| Always included when detected Keys from `OTEL_RESOURCE_ATTRIBUTES`| Custom attributes you set, such as `department` or `team.id`. See Multi-team organization support| `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES` (default: true) -Events additionally include the following attributes. These are never attached to metrics because they would cause unbounded cardinality: +When Claude Code is signed in to a [Claude apps gateway](</docs/en/claude-apps-gateway>), the CLI stamps exports with the authenticated identity from the gateway session: `user.id` is the IdP subject rather than an anonymous installation identifier, `user.email` is the signed-in email, and `user.groups` carries IdP group membership as a comma-separated string. Each export also carries `identity.source: gateway-oidc`. The gateway identity is applied last, so `user.*` and `identity.*` keys set through `OTEL_RESOURCE_ATTRIBUTES` are ignored on gateway sessions. Events additionally include the following attributes. These are never attached to metrics because they would cause unbounded cardinality: * `prompt.id`: UUID correlating a user prompt with all subsequent events until the next prompt. See Event correlation attributes. * `workspace.host_paths`: host workspace directories selected in the desktop app, as a string array @@ -590,6 +591,24 @@ * `prompt`: Prompt content. Redacted by default. Set `OTEL_LOG_USER_PROMPTS=1` to include it * `command_name`: Command name when the prompt invokes one. Built-in and bundled command names such as `compact` or `debug` are emitted as-is; aliases such as `reset` emit as typed rather than the canonical name. Custom, plugin, and MCP command names collapse to `custom` or `mcp` unless `OTEL_LOG_TOOL_DETAILS=1` is set * `command_source`: Origin of the command when present: `builtin`, `custom`, or `mcp`. Plugin-provided commands report as `custom` + +#### + +​ + +Assistant response event + +Logged after each API request that returns text content from the model. Only the response’s text blocks are included; thinking blocks and tool-use blocks are excluded. Requires Claude Code v2.1.193 or later. **Event Name** : `claude_code.assistant_response` **Attributes** : + + * All standard attributes + * `event.name`: `"assistant_response"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `response_length`: Length of the response text in characters + * `response`: Response text, truncated at 60 KB. Redacted to `<REDACTED>` by default. Set `OTEL_LOG_ASSISTANT_RESPONSES=1` to include it. When `OTEL_LOG_ASSISTANT_RESPONSES` is unset, `OTEL_LOG_USER_PROMPTS` controls it instead, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` to keep responses redacted while prompt logging is on + * `model`: Model identifier (for example, “claude-sonnet-4-6”) + * `request_id`: Anthropic API request ID from the response’s `request-id` header. Present only when the API returns one + * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name #### @@ -1136,7 +1155,7 @@ Attribute actions to users -The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account, plus the installation-scoped `user.id` and the per-session `session.id`. MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code doesn’t act under a separate service account; the identity recorded on each event is the developer’s own Claude account. When Claude Code authenticates with a direct API key, or against Bedrock, Vertex AI, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper: +The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account, plus `user.id` and the per-session `session.id`. `user.id` is an installation-scoped identifier, except on [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, where it is the IdP subject from the gateway-issued token. MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code doesn’t act under a separate service account; the identity recorded on each event is the developer’s own Claude account, or the developer’s IdP identity on a [Claude apps gateway](</docs/en/claude-apps-gateway>) session. When Claude Code authenticates with a direct API key, or against Bedrock, Vertex AI, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper. Claude apps gateway sessions need none of this: the CLI stamps the IdP identity automatically, as described in Standard attributes. export OTEL_RESOURCE_ATTRIBUTES="enduser.id=jdoe@example.com,enduser.directory_id=S-1-5-21-..." @@ -1274,6 +1293,7 @@ * Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` + * Assistant response text is not collected by default. Only response length is recorded. To include response text, set `OTEL_LOG_ASSISTANT_RESPONSES=1`. Like all OpenTelemetry data from Claude Code, the response text is sent only to the OTel endpoint you configure, never to Anthropic. When this variable is unset, `OTEL_LOG_USER_PROMPTS` is used as a fallback, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` if you want prompt content without response content * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. This data is sent only to the OTEL endpoint you configure, never to Anthropic. Arguments may still contain sensitive values, so configure your telemetry backend to filter or redact these attributes as needed. When enabled: * `tool_result` and `tool_decision` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names. Fields such as `full_command` are emitted untruncated * `tool_result` events additionally include a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters
modified
Show diff (200 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -52,9 +52,9 @@ } } -Managed settings can be distributed via MDM (Mobile Device Management) or other device management solutions. Environment variables defined in the managed settings file have high precedence and cannot be overridden by users. - -Claude Code does not pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool does not inherit Claude Code’s exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry. +Managed settings can be distributed via MDM (Mobile Device Management) or other device management solutions. Environment variables defined in the managed settings file have high precedence and can’t be overridden by users. + +Claude Code doesn’t pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool doesn’t inherit Claude Code’s exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry. ## @@ -311,7 +311,7 @@ # Add custom attributes for team identification export OTEL_RESOURCE_ATTRIBUTES="department=engineering,team.id=platform,cost_center=eng-123" -These custom attributes will be included in all metrics and events, allowing you to: +These custom attributes are included in all metrics and events, allowing you to: * Filter metrics by team or department * Track costs per cost center @@ -320,26 +320,23 @@ Claude Code attaches these values as attributes on every metric datapoint and event record, in addition to sending them in the OTLP resource block. Because most metrics backends expose datapoint attributes as queryable labels, you can group and filter metrics by your custom keys directly. Custom keys never override the standard attributes such as `user.id` or `session.id`: when a key collides, Claude Code keeps the built-in value. Each custom key becomes a label on every metric series, so high-cardinality values increase storage cost in your metrics backend. To send custom attributes in the resource block only and omit them from datapoint labels, set `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES=false`. See Metrics cardinality control. -**Important formatting requirements for OTEL_RESOURCE_ATTRIBUTES:** The `OTEL_RESOURCE_ATTRIBUTES` environment variable uses comma-separated key=value pairs with strict formatting requirements: - - * **No spaces allowed** : Values cannot contain spaces. For example, `user.organizationName=My Company` is invalid - * **Format** : Must be comma-separated key=value pairs: `key1=value1,key2=value2` - * **Allowed characters** : Only US-ASCII characters excluding control characters, whitespace, double quotes, commas, semicolons, and backslashes - * **Special characters** : Characters outside the allowed range must be percent-encoded - -**Examples:** - - # ❌ Invalid - contains spaces - export OTEL_RESOURCE_ATTRIBUTES="org.name=John's Organization" - - # ✅ Valid - use underscores or camelCase instead +The `OTEL_RESOURCE_ATTRIBUTES` environment variable uses comma-separated key=value pairs with strict formatting requirements: + + * **No spaces allowed** : values can’t contain spaces. For example, `user.organizationName=My Company` is invalid + * **Format** : must be comma-separated key=value pairs: `key1=value1,key2=value2` + * **Allowed characters** : only US-ASCII characters excluding control characters, whitespace, double quotes, commas, semicolons, and backslashes + * **Special characters** : characters outside the allowed range must be percent-encoded + +For a value that would need a space, use underscores or camelCase instead. The following examples set `org.name` with each form: + export OTEL_RESOURCE_ATTRIBUTES="org.name=Johns_Organization" export OTEL_RESOURCE_ATTRIBUTES="org.name=JohnsOrganization" - # ✅ Valid - percent-encode special characters if needed +You can percent-encode any character, not only the excluded ones. This example encodes both the space and the apostrophe: + export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization" -Note: wrapping values in quotes doesn’t escape spaces. For example, `org.name="My Company"` results in the literal value `"My Company"` (with quotes included), not `My Company`. +Wrapping values in quotes doesn’t escape spaces. For example, `org.name="My Company"` results in the literal value `"My Company"` with the quotes included, not `My Company`. ### @@ -504,7 +501,7 @@ * `model`: Model identifier (for example, “claude-sonnet-4-6”) * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise - * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model does not support effort. + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model doesn’t support effort. * `agent.name`: Subagent type that issued the request. Built-in agent names and agents from official-marketplace plugins appear verbatim. Other user-defined agent names are replaced with `"custom"`. Absent when the request was not issued by a named subagent type. * `skill.name`: Skill active for the request, set by the Skill tool, a `/` command, or inherited by a spawned subagent. Built-in, bundled, user-defined, and official-marketplace plugin skill names appear verbatim. Third-party plugin skill names are replaced with `"third-party"`. Absent when no skill is active. * `plugin.name`: Owning plugin when the active skill or subagent is provided by a plugin. Official-marketplace plugin names appear verbatim. Third-party plugin names are replaced with `"third-party"`. Absent when neither the skill nor the subagent has an owning plugin. @@ -548,7 +545,7 @@ Active time counter -Tracks actual time spent actively using Claude Code, excluding idle time. This metric is incremented during user interactions (typing, reading responses) and during CLI processing (tool execution, AI response generation). **Attributes** : +Tracks actual time spent actively using Claude Code, excluding idle time. This metric is incremented during user interactions, such as typing and reading responses, and during CLI processing, such as tool execution and AI response generation. **Attributes** : * All standard attributes * `type`: `"user"` for keyboard interactions, `"cli"` for tool execution and AI responses @@ -590,7 +587,7 @@ * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session * `prompt_length`: Length of the prompt - * `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`) + * `prompt`: Prompt content. Redacted by default. Set `OTEL_LOG_USER_PROMPTS=1` to include it * `command_name`: Command name when the prompt invokes one. Built-in and bundled command names such as `compact` or `debug` are emitted as-is; aliases such as `reset` emit as typed rather than the canonical name. Custom, plugin, and MCP command names collapse to `custom` or `mcp` unless `OTEL_LOG_TOOL_DETAILS=1` is set * `command_source`: Origin of the command when present: `builtin`, `custom`, or `mcp`. Plugin-provided commands report as `custom` @@ -612,7 +609,7 @@ * `duration_ms`: Execution time in milliseconds * `error_type`: Error category string when the tool failed, such as `"Error:ENOENT"` or `"ShellError"` * `error` (when `OTEL_LOG_TOOL_DETAILS=1`): Full error message when the tool failed - * `decision_type`: Always `"accept"`, since this event is only emitted after the tool runs (rejected calls don’t produce a tool result) + * `decision_type`: Always `"accept"`, since this event is only emitted after the tool runs. Rejected calls don’t produce a tool result * `decision_source`: Where the permission decision came from. One of `"config"`, `"hook"`, `"user_permanent"`, or `"user_temporary"`. See the Tool decision event for what each value means. The reject-only sources `"user_abort"` and `"user_reject"` never appear on this event. * `tool_input_size_bytes`: Size of the JSON-serialized tool input in bytes * `tool_result_size_bytes`: Size of the tool result in bytes @@ -647,7 +644,7 @@ * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name - * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model does not support effort. + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model doesn’t support effort. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. #### @@ -670,7 +667,7 @@ * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name - * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when the model does not support effort. + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when the model doesn’t support effort. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. #### @@ -679,7 +676,7 @@ API refusal event -Logged when an API request returns `stop_reason: "refusal"`. Refusals arrive on a successful response stream rather than as an HTTP error, so the `api_error` event does not fire for them. This event lets you track refusal frequency and group refusals by the same attributes as `api_request` and `api_error`. **Event Name** : `claude_code.api_refusal` **Attributes** : +Logged when an API request returns `stop_reason: "refusal"`. Refusals arrive on a successful response stream rather than as an HTTP error, so the `api_error` event doesn’t fire for them. This event lets you track refusal frequency and group refusals by the same attributes as `api_request` and `api_error`. **Event Name** : `claude_code.api_refusal` **Attributes** : * All standard attributes * `event.name`: `"api_refusal"` @@ -690,9 +687,9 @@ * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name. See `api_request` for definitions. * `speed`: Either `"fast"` when [Fast mode](</docs/en/fast-mode>) is active, or `"normal"` * `attempt`: Retry attempt number. The first attempt is `1`. - * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when the model does not support effort. + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when the model doesn’t support effort. * `server_fallback_hop`: `true` when the API’s server-side model fallback already retried this refusal on a different model, so the user did not see this particular refusal. `false` when the request ended in a refusal. A single turn can emit both a `true` hop event and a later `false` final event when the fallback model also refuses. - * `has_category`: `true` when the API response carried a `stop_details.category` of `"cyber"`, `"bio"`, `"frontier_llm"`, or `"reasoning_extraction"`. `false` when the response carried no category or a value outside that set. Absent when `server_fallback_hop` is `true`, because hop blocks do not carry `stop_details`. + * `has_category`: `true` when the API response carried a `stop_details.category` of `"cyber"`, `"bio"`, `"frontier_llm"`, or `"reasoning_extraction"`. `false` when the response carried no category or a value outside that set. Absent when `server_fallback_hop` is `true`, because hop blocks don’t carry `stop_details`. * `has_explanation`: `true` when the API response carried a `stop_details.explanation`, otherwise `false`. Absent when `server_fallback_hop` is `true`. * `category`: The `stop_details.category` value from the API response. One of `"cyber"`, `"bio"`, `"frontier_llm"`, or `"reasoning_extraction"`. Only present when `OTEL_LOG_TOOL_DETAILS=1` is set and `has_category` is `true`. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. @@ -752,7 +749,7 @@ * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. * `decision`: Either `"accept"` or `"reject"` * `source`: Where the decision came from: - * `"config"`: Decided automatically without prompting, based on project settings, allow or deny rules in the user’s personal settings, enterprise managed policy, `--allowedTools` or `--disallowedTools` flags, the active permission mode, a session-scoped grant from an earlier prompt in the same interactive CLI session, or because the tool is inherently safe. The event does not indicate which of these sources matched. + * `"config"`: Decided automatically without prompting, based on project settings, allow or deny rules in the user’s personal settings, enterprise managed policy, `--allowedTools` or `--disallowedTools` flags, the active permission mode, a session-scoped grant from an earlier prompt in the same interactive CLI session, or because the tool is inherently safe. The event doesn’t indicate which of these sources matched. * `"hook"`: A `PreToolUse` or `PermissionRequest` hook returned the decision. * `"user_permanent"`: Emitted when the user chose “Yes, and don’t ask again for …” at a permission prompt, which saves an allow rule to their personal settings. In the interactive CLI this is emitted only for that choice itself; later calls that match the saved rule emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the initial choice and later rule matches emit `"user_permanent"`. Treated as an accept. * `"user_temporary"`: Emitted when the user chose “Yes” at a permission prompt for a one-time approval, or chose one of the ”… during this session” options on a file edit or read prompt. In the interactive CLI this is emitted only for the choice itself; later calls allowed by that session-scoped grant emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the choice and later matches emit `"user_temporary"`. Treated as an accept. @@ -879,7 +876,7 @@ * `skill_path_count`: number of skill directories the plugin declares * `command_path_count`: number of command directories the plugin declares * `agent_path_count`: number of agent directories the plugin declares - * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. In safe mode this event reports configured inventory only; the plugin’s commands, skills, hooks, and MCP servers do not load. Requires Claude Code v2.1.169 or later + * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. In safe mode this event reports configured inventory only; the plugin’s commands, skills, hooks, and MCP servers don’t load. Requires Claude Code v2.1.169 or later #### @@ -1005,7 +1002,7 @@ Hook plugin metrics event -Logged when an official-marketplace plugin hook emits per-invocation metrics. Only plugins installed from an official Anthropic marketplace can emit these. Third-party marketplace plugins and user-configured hooks do not emit to this event. Use this event to monitor plugin behavior such as finding rates, costs, and durations from your own observability stack. **Event Name** : `claude_code.hook_plugin_metrics` **Attributes** : +Logged when an official-marketplace plugin hook emits per-invocation metrics. Only plugins installed from an official Anthropic marketplace can emit these. Third-party marketplace plugins and user-configured hooks don’t emit to this event. Use this event to monitor plugin behavior such as finding rates, costs, and durations from your own observability stack. **Event Name** : `claude_code.hook_plugin_metrics` **Attributes** : * All standard attributes * `event.name`: `"hook_plugin_metrics"` @@ -1116,14 +1113,14 @@ Event analysis -The event data provides detailed insights into Claude Code interactions: **Tool Usage Patterns** : analyze tool result events to identify: +The event data provides detailed insights into Claude Code interactions: **Tool usage patterns** : analyze tool result events to identify: * Most frequently used tools * Tool success rates * Average tool execution times * Error patterns by tool type -**Performance Monitoring** : track API request durations and tool execution times to identify performance bottlenecks. +**Performance monitoring** : track API request durations and tool execution times to identify performance bottlenecks. ## @@ -1131,7 +1128,7 @@ Audit security events -OpenTelemetry events are the audit data source for Claude Code activity. Every event carries identity attributes that tie tool calls, MCP activity, and permission decisions back to the user who triggered them, and the OTLP logs exporter can deliver these events to any Security Information and Event Management (SIEM) platform with an OTLP receiver or to an OpenTelemetry Collector that forwards to your SIEM. +OpenTelemetry events are the audit data source for Claude Code activity. Every event carries identity attributes that tie tool calls, MCP activity, and permission decisions back to the user who triggered them. The OTLP logs exporter can deliver these events to any Security Information and Event Management (SIEM) platform with an OTLP receiver, or to an OpenTelemetry Collector that forwards to your SIEM. ### @@ -1139,7 +1136,7 @@ Attribute actions to users -The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account, plus the installation-scoped `user.id` and the per-session `session.id`. MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code does not act under a separate service account; the identity recorded on each event is the developer’s own Claude account. When Claude Code authenticates with a direct API key, or against Bedrock, Vertex AI, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper: +The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account, plus the installation-scoped `user.id` and the per-session `session.id`. MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code doesn’t act under a separate service account; the identity recorded on each event is the developer’s own Claude account. When Claude Code authenticates with a direct API key, or against Bedrock, Vertex AI, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper: export OTEL_RESOURCE_ATTRIBUTES="enduser.id=jdoe@example.com,enduser.directory_id=S-1-5-21-..."
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -458,7 +458,7 @@ Incremented at the start of each session. **Attributes** : * All standard attributes - * `start_type`: How the session was started. One of `"fresh"`, `"resume"`, or `"continue"` + * `start_type`: How the session was started. One of `"fresh"`, `"resume"`, `"continue"`, or `"agents_view"`. The `"agents_view"` value identifies the `claude agents` dashboard process, a user-launched local UI rather than a conversational session. Filter on this value to separate UI process launches from conversational sessions in your dashboards. #### @@ -1100,7 +1100,7 @@ * Unusual token consumption * High session volume from specific users -All metrics can be segmented by the standard attributes. The `model` attribute is available on `claude_code.token.usage`, `claude_code.cost.usage`, and from v2.1.172, `claude_code.lines_of_code.count`. Per-model breakdowns of commits can only be approximated by joining against the token or cost metrics on `session.id`, since one session can span multiple models. +All metrics can be segmented by the standard attributes. The `model` attribute is available on `claude_code.token.usage`, `claude_code.cost.usage`, and from v2.1.172, `claude_code.lines_of_code.count`. Per-model breakdowns of commits can only be approximated by joining against the token or cost metrics on `session.id`, since one session can span multiple models. Filter the token or cost side to rows where `query_source` is `"main"` so auxiliary and subagent requests don’t attribute the session’s commits to a model that didn’t make them. ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1108,7 +1108,7 @@ Detect retry exhaustion -Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records how many attempts were made in total. A value greater than `CLAUDE_CODE_MAX_RETRIES` (default `10`, capped at `15`) indicates the request exhausted all retries on a transient error. A lower value indicates a non-retryable error such as a `400` response. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. +Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records how many attempts were made in total. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15. When the request exhausts all retries on a transient error, `attempt` equals one more than that effective limit: 11 by default, and never more than 16. A lower value indicates a non-retryable error such as a `400` response. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1108,7 +1108,7 @@ Detect retry exhaustion -Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records how many attempts were made in total. A value greater than `CLAUDE_CODE_MAX_RETRIES` (default `10`) indicates the request exhausted all retries on a transient error. A lower value indicates a non-retryable error such as a `400` response. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. +Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records how many attempts were made in total. A value greater than `CLAUDE_CODE_MAX_RETRIES` (default `10`, capped at `15`) indicates the request exhausted all retries on a transient error. A lower value indicates a non-retryable error such as a `400` response. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -679,7 +679,7 @@ API refusal event -Logged when an API request returns `stop_reason: "refusal"`. Refusals arrive on a successful response stream rather than as an HTTP error, so the `api_error` event does not fire for them. This event lets you track refusal frequency. **Event Name** : `claude_code.api_refusal` **Attributes** : +Logged when an API request returns `stop_reason: "refusal"`. Refusals arrive on a successful response stream rather than as an HTTP error, so the `api_error` event does not fire for them. This event lets you track refusal frequency and group refusals by the same attributes as `api_request` and `api_error`. **Event Name** : `claude_code.api_refusal` **Attributes** : * All standard attributes * `event.name`: `"api_refusal"` @@ -687,6 +687,15 @@ * `event.sequence`: monotonically increasing counter for ordering events within a session * `model`: Model identifier from the request * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. + * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name. See `api_request` for definitions. + * `speed`: Either `"fast"` when [Fast mode](</docs/en/fast-mode>) is active, or `"normal"` + * `attempt`: Retry attempt number. The first attempt is `1`. + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when the model does not support effort. + * `server_fallback_hop`: `true` when the API’s server-side model fallback already retried this refusal on a different model, so the user did not see this particular refusal. `false` when the request ended in a refusal. A single turn can emit both a `true` hop event and a later `false` final event when the fallback model also refuses. + * `has_category`: `true` when the API response carried a `stop_details.category` of `"cyber"`, `"bio"`, `"frontier_llm"`, or `"reasoning_extraction"`. `false` when the response carried no category or a value outside that set. Absent when `server_fallback_hop` is `true`, because hop blocks do not carry `stop_details`. + * `has_explanation`: `true` when the API response carried a `stop_details.explanation`, otherwise `false`. Absent when `server_fallback_hop` is `true`. + * `category`: The `stop_details.category` value from the API response. One of `"cyber"`, `"bio"`, `"frontier_llm"`, or `"reasoning_extraction"`. Only present when `OTEL_LOG_TOOL_DETAILS=1` is set and `has_category` is `true`. + * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. ####
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -470,6 +470,7 @@ * All standard attributes * `type`: (`"added"`, `"removed"`) + * `model`: Model identifier for the model that made the change (for example, “claude-sonnet-4-6”). Requires Claude Code v2.1.172 or later #### @@ -865,6 +866,7 @@ * `plugin_id_hash`: deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count how many distinct third-party plugins are loaded across your fleet without recording their names * `has_hooks`: whether the plugin contributes hooks * `has_mcp`: whether the plugin contributes MCP servers + * `host_owned_mcp`: `true` when the SDK host manages this plugin’s MCP connections and Claude Code skipped reading the plugin’s MCP server configuration, `false` otherwise. Requires Claude Code v2.1.172 or later * `skill_path_count`: number of skill directories the plugin declares * `command_path_count`: number of command directories the plugin declares * `agent_path_count`: number of agent directories the plugin declares @@ -1060,7 +1062,7 @@ ---|--- `claude_code.token.usage`| Break down by `type` (input/output), user, team, model, `skill.name`, `plugin.name`, or `agent.name` `claude_code.session.count`| Track adoption and engagement over time -`claude_code.lines_of_code.count`| Measure productivity by tracking code additions/removals +`claude_code.lines_of_code.count`| Measure productivity by tracking code additions and removals, broken down by model `claude_code.commit.count` & `claude_code.pull_request.count`| Understand impact on development workflows ### @@ -1089,7 +1091,7 @@ * Unusual token consumption * High session volume from specific users -All metrics can be segmented by the standard attributes. The `model` attribute is available on `claude_code.token.usage` and `claude_code.cost.usage` only; activity counters have never carried it. Per-model breakdowns of lines of code or commits can only be approximated by joining against the token or cost metrics on `session.id`, since one session can span multiple models. +All metrics can be segmented by the standard attributes. The `model` attribute is available on `claude_code.token.usage`, `claude_code.cost.usage`, and from v2.1.172, `claude_code.lines_of_code.count`. Per-model breakdowns of commits can only be approximated by joining against the token or cost metrics on `session.id`, since one session can span multiple models. ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1207,7 +1207,7 @@ * **Time series databases (for example, Prometheus)** : Rate calculations, aggregated metrics * **Columnar stores (for example, ClickHouse)** : Complex queries, unique user analysis - * **Full-featured observability platforms (for example, Honeycomb, Datadog)** : Advanced querying, visualization, alerting + * **Full-featured observability platforms (for example, Honeycomb, Datadog, Grafana Cloud)** : Advanced querying, visualization, alerting ### @@ -1217,7 +1217,7 @@ * **Log aggregation systems (for example, Elasticsearch, Loki)** : Full-text search, log analysis * **Columnar stores (for example, ClickHouse)** : Structured event analysis - * **Full-featured observability platforms (for example, Honeycomb, Datadog)** : Correlation between metrics and events + * **Full-featured observability platforms (for example, Honeycomb, Datadog, Grafana Cloud)** : Correlation between metrics and events ### @@ -1228,7 +1228,7 @@ Choose a backend that supports distributed trace storage and span correlation: * **Distributed tracing systems (for example, Jaeger, Zipkin, Grafana Tempo)** : Span visualization, request waterfalls, latency analysis - * **Full-featured observability platforms (for example, Honeycomb, Datadog)** : Trace search and correlation with metrics and logs + * **Full-featured observability platforms (for example, Honeycomb, Datadog, Grafana Cloud)** : Trace search and correlation with metrics and logs For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries.
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -412,7 +412,7 @@ `organization.id`| Organization UUID (when authenticated)| Always included when available `user.account_uuid`| Account UUID (when authenticated)| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) `user.account_id`| Account ID in tagged format matching Anthropic admin APIs (when authenticated), such as `user_01BWBeN28...`| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) -`user.id`| Anonymous device/installation identifier, generated per Claude Code installation| Always included +`user.id`| Random anonymous identifier generated on first run and persisted in `~/.claude.json`. It contains no personal information and is not derived from your Claude account. Deleting the file produces a new unrelated value on next run.| Always included `user.email`| User email address (when authenticated via OAuth)| Always included when available `terminal.type`| Terminal type, such as `iTerm.app`, `vscode`, `cursor`, or `tmux`| Always included when detected Keys from `OTEL_RESOURCE_ATTRIBUTES`| Custom attributes you set, such as `department` or `team.id`. See Multi-team organization support| `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES` (default: true) @@ -868,6 +868,7 @@ * `skill_path_count`: number of skill directories the plugin declares * `command_path_count`: number of command directories the plugin declares * `agent_path_count`: number of agent directories the plugin declares + * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. In safe mode this event reports configured inventory only; the plugin’s commands, skills, hooks, and MCP servers do not load. Requires Claude Code v2.1.169 or later #### @@ -937,6 +938,7 @@ * `hook_event`: hook event type, such as `"PreToolUse"` or `"PostToolUse"` * `hook_type`: hook implementation type: `"command"`, `"prompt"`, `"mcp_tool"`, `"http"`, or `"agent"` * `hook_source`: where the hook is defined: `"userSettings"`, `"projectSettings"`, `"localSettings"`, `"flagSettings"`, `"policySettings"`, or `"pluginHook"` + * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. Requires Claude Code v2.1.169 or later * `hook_matcher` (when `OTEL_LOG_TOOL_DETAILS=1`): the matcher string from the hook configuration, when one is set * `plugin.name` (when `hook_source` is `"pluginHook"`): name of the contributing plugin. For plugins outside the official marketplace and built-in bundle the value is `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` * `plugin_id_hash` (when `hook_source` is `"pluginHook"`): deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count distinct contributing plugins without recording their names @@ -958,6 +960,7 @@ * `num_hooks`: Number of matching hook commands * `managed_only`: `"true"` when only managed-policy hooks are permitted * `hook_source`: `"policySettings"` or `"merged"` + * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. Requires Claude Code v2.1.169 or later * `hook_definitions`: JSON-serialized hook configuration. Included only when both detailed beta tracing and `OTEL_LOG_TOOL_DETAILS=1` are enabled #### @@ -982,6 +985,7 @@ * `total_duration_ms`: Wall-clock duration of all matching hooks * `managed_only`: `"true"` when only managed-policy hooks are permitted * `hook_source`: `"policySettings"` or `"merged"` + * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. Requires Claude Code v2.1.169 or later * `hook_definitions`: JSON-serialized hook configuration. Included only when both detailed beta tracing and `OTEL_LOG_TOOL_DETAILS=1` are enabled #### @@ -1085,7 +1089,7 @@ * Unusual token consumption * High session volume from specific users -All metrics can be segmented by `user.account_uuid`, `user.account_id`, `organization.id`, `session.id`, `model`, and `app.version`. +All metrics can be segmented by the standard attributes. The `model` attribute is available on `claude_code.token.usage` and `claude_code.cost.usage` only; activity counters have never carried it. Per-model breakdowns of lines of code or commits can only be approximated by joining against the token or cost metrics on `session.id`, since one session can span multiple models. ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -676,6 +676,21 @@ ​ +API refusal event + +Logged when an API request returns `stop_reason: "refusal"`. Refusals arrive on a successful response stream rather than as an HTTP error, so the `api_error` event does not fire for them. This event lets you track refusal frequency. **Event Name** : `claude_code.api_refusal` **Attributes** : + + * All standard attributes + * `event.name`: `"api_refusal"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `model`: Model identifier from the request + * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. + +#### + +​ + API request body event Logged for each API request attempt when `OTEL_LOG_RAW_API_BODIES` is set. One event is emitted per attempt, so retries with adjusted parameters each produce their own event. **Event Name** : `claude_code.api_request_body` **Attributes** : @@ -791,6 +806,9 @@ * `server_scope`: Scope the server is configured at, such as `"user"`, `"project"`, or `"local"` * `duration_ms`: Connection attempt duration in milliseconds * `error_code`: Error code when the connection failed + * `is_plugin`: `true` when the server is provided by a plugin, `false` otherwise + * `plugin_id_hash` (when `is_plugin` is `true`): Stable hash of the plugin name and marketplace, for grouping events by plugin without exposing the name + * `plugin.name` (when `is_plugin` is `true`): Name of the plugin that provides the server. For third-party plugins this is the literal string `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1`; this protects third-party plugin names from appearing in logs by default. Plugins from official Anthropic sources are always identified by name. The `plugin_id_hash` and `plugin.name` attributes flow to your own monitoring backend and are not sent to Anthropic * `server_name` (when `OTEL_LOG_TOOL_DETAILS=1`): Configured server name * `error` (when `OTEL_LOG_TOOL_DETAILS=1`): Full error message when the connection failed @@ -1128,7 +1146,7 @@ * `tool_result`: keeps `tool_name` and `mcp_server_scope`, omits `mcp_server_name`, `mcp_tool_name`, and arguments * `tool_decision`: keeps `tool_name`, omits `tool_parameters` - * `mcp_server_connection`: omits `server_name` and the error message + * `mcp_server_connection`: omits `server_name` and the error message, but keeps `is_plugin`, `plugin_id_hash`, and `plugin.name`, with non-Anthropic plugin names redacted to the literal `"third-party"`, so plugin-provided servers remain distinguishable without detailed logging ### @@ -1144,7 +1162,7 @@ Permission mode escalation| `permission_mode_changed`| `from_mode`, `to_mode`, `trigger` Policy hook blocked an action| `hook_execution_complete`| `hook_event`, `num_blocking` Login, logout, and authentication failure| `auth`| `action`, `success`, `error_category` -MCP server connect or failure| `mcp_server_connection`| `status`, `server_name`, `error_code` +MCP server connect or failure| `mcp_server_connection`| `status`, `server_name`, `is_plugin`, `error_code` Plugin installed and its source| `plugin_installed`| `plugin.name`, `marketplace.name`, `marketplace.is_official` Commands run and files touched| `tool_result` (executed) or `tool_decision` (rejected) with `OTEL_LOG_TOOL_DETAILS=1`| `tool_parameters`; `tool_input` (`tool_result` only)
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -211,6 +211,8 @@ `result_tokens`| Approximate token size of the tool result| `agent_id`| Identifier of the subagent or teammate that ran the tool. Absent on the main session| `parent_agent_id`| Identifier of the agent that spawned this one. Absent for the main session and for agents spawned directly from it| +`tool_use_id`| The model’s `tool_use` block id for this call. Matches the `tool_use_id` on the tool_result and tool_decision events and in hook payloads, so you can join the span to those records| +`gen_ai.tool.call.id`| Same value as `tool_use_id`. OpenTelemetry GenAI semantic convention| `file_path`| Target file path for Read, Edit, and Write tools| `OTEL_LOG_TOOL_DETAILS` `full_command`| Command string for the Bash tool| `OTEL_LOG_TOOL_DETAILS` `skill_name`| Skill name for the Skill tool| `OTEL_LOG_TOOL_DETAILS` @@ -229,6 +231,8 @@ Attribute| Description| Gated by ---|---|--- `duration_ms`| Time spent running the tool body| +`tool_use_id`| Same value as on the parent `claude_code.tool` span| +`gen_ai.tool.call.id`| Same value as `tool_use_id`. OpenTelemetry GenAI semantic convention| `success`| `true` or `false`| `error`| Error category string when execution failed, such as `Error:ENOENT` or `ShellError`. Contains the full error message instead when the gate is set| `OTEL_LOG_TOOL_DETAILS` @@ -862,6 +866,7 @@ * `skill.name`: Name of the skill. For user-defined and third-party plugin skills the value is the placeholder `"custom_skill"` unless `OTEL_LOG_TOOL_DETAILS=1` * `invocation_trigger`: How the skill was triggered (`"user-slash"`, `"claude-proactive"`, or `"nested-skill"`) * `skill.source`: Where the skill was loaded from (for example, `"bundled"`, `"userSettings"`, `"projectSettings"`, `"plugin"`) + * `skill.kind`: `"workflow"` when the skill is a workflow skill. Absent otherwise * `plugin.name` (when `OTEL_LOG_TOOL_DETAILS=1` or the plugin is from an official marketplace): Name of the owning plugin when the skill is provided by a plugin * `marketplace.name` (when `OTEL_LOG_TOOL_DETAILS=1` or the plugin is from an official marketplace): Marketplace the owning plugin was installed from, when the skill is provided by a plugin
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.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. - Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, events via the logs/events protocol, and optionally distributed traces via the traces protocol. Configure your metrics, logs, and traces backends to match your monitoring requirements. ## @@ -124,6 +118,7 @@ `OTEL_METRICS_INCLUDE_VERSION`| Include app.version attribute in metrics| `false`| `true` `OTEL_METRICS_INCLUDE_ACCOUNT_UUID`| Include user.account_uuid and user.account_id attributes in metrics| `true`| `false` `OTEL_METRICS_INCLUDE_ENTRYPOINT`| Include app.entrypoint attribute in metrics| `false`| `true` +`OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES`| Include keys from `OTEL_RESOURCE_ATTRIBUTES` as attributes on metric datapoints| `true`| `false` These variables help control the cardinality of metrics, which affects storage requirements and query performance in your metrics backend. Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. @@ -319,6 +314,8 @@ * Create team-specific dashboards * Set up alerts for specific teams +Claude Code attaches these values as attributes on every metric datapoint and event record, in addition to sending them in the OTLP resource block. Because most metrics backends expose datapoint attributes as queryable labels, you can group and filter metrics by your custom keys directly. Custom keys never override the standard attributes such as `user.id` or `session.id`: when a key collides, Claude Code keeps the built-in value. Each custom key becomes a label on every metric series, so high-cardinality values increase storage cost in your metrics backend. To send custom attributes in the resource block only and omit them from datapoint labels, set `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES=false`. See Metrics cardinality control. + **Important formatting requirements for OTEL_RESOURCE_ATTRIBUTES:** The `OTEL_RESOURCE_ATTRIBUTES` environment variable uses comma-separated key=value pairs with strict formatting requirements: * **No spaces allowed** : Values cannot contain spaces. For example, `user.organizationName=My Company` is invalid @@ -414,6 +411,7 @@ `user.id`| Anonymous device/installation identifier, generated per Claude Code installation| Always included `user.email`| User email address (when authenticated via OAuth)| Always included when available `terminal.type`| Terminal type, such as `iTerm.app`, `vscode`, `cursor`, or `tmux`| Always included when detected +Keys from `OTEL_RESOURCE_ATTRIBUTES`| Custom attributes you set, such as `department` or `team.id`. See Multi-team organization support| `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES` (default: true) Events additionally include the following attributes. These are never attached to metrics because they would cause unbounded cardinality:
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -151,7 +151,7 @@ Span hierarchy -Each user prompt starts a `claude_code.interaction` root span. API calls, tool calls, and hook executions are recorded as its children. Tool spans have two child spans of their own: one for the time spent waiting on a permission decision and one for the execution itself. When the Task tool spawns a subagent, the subagent’s API and tool spans nest under the parent’s `claude_code.tool` span. +Each user prompt starts a `claude_code.interaction` root span. API calls, tool calls, and hook executions are recorded as its children. Tool spans have two child spans of their own: one for the time spent waiting on a permission decision and one for the execution itself. When the Agent tool, or legacy Task tool, spawns a subagent, the subagent’s API and tool spans nest under the parent’s `claude_code.tool` span. claude_code.interaction ├── claude_code.llm_request @@ -159,7 +159,7 @@ └── claude_code.tool ├── claude_code.tool.blocked_on_user ├── claude_code.tool.execution - └── (Task tool) subagent claude_code.llm_request / claude_code.tool spans + └── (Agent tool) subagent claude_code.llm_request / claude_code.tool spans In Agent SDK and `claude -p` sessions, `claude_code.interaction` itself becomes a child of the caller’s span when `TRACEPARENT` is set in the environment. @@ -219,7 +219,7 @@ `file_path`| Target file path for Read, Edit, and Write tools| `OTEL_LOG_TOOL_DETAILS` `full_command`| Command string for the Bash tool| `OTEL_LOG_TOOL_DETAILS` `skill_name`| Skill name for the Skill tool| `OTEL_LOG_TOOL_DETAILS` -`subagent_type`| Subagent type for the Task tool| `OTEL_LOG_TOOL_DETAILS` +`subagent_type`| Subagent type for the Agent tool or legacy Task tool| `OTEL_LOG_TOOL_DETAILS` When `OTEL_LOG_TOOL_CONTENT=1`, this span also records a `tool.output` span event whose attributes contain the tool’s input and output bodies, truncated at 60 KB per attribute. **`claude_code.tool.blocked_on_user`** @@ -616,9 +616,10 @@ * `mcp_server_scope`: MCP server scope identifier (for MCP tools) * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters: * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds) + * For WorkspaceBash tool: includes `bash_command`, `full_command`, `timeout` * For MCP tools: includes `mcp_server_name`, `mcp_tool_name` * For Skill tool: includes `skill_name` - * For Task tool: includes `subagent_type` + * For Agent tool or legacy Task tool: includes `subagent_type` * `tool_input` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON-serialized tool arguments. Individual values over 512 characters are truncated, and the full payload is bounded to ~4 K characters. Applies to all tools including MCP tools. #### @@ -730,6 +731,12 @@ * `"user_temporary"`: Emitted when the user chose “Yes” at a permission prompt for a one-time approval, or chose one of the ”… during this session” options on a file edit or read prompt. In the interactive CLI this is emitted only for the choice itself; later calls allowed by that session-scoped grant emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the choice and later matches emit `"user_temporary"`. Treated as an accept. * `"user_abort"`: Emitted when the user dismissed the permission prompt without answering. Treated as a reject. * `"user_reject"`: Emitted when the user chose “No” when prompted. In the interactive CLI this is emitted only for that choice itself; calls that match a deny rule in the user’s personal settings emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, calls that match a deny rule in personal settings emit `"user_reject"`. Treated as a reject. + * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters. Same shape as the Tool result event, minus post-execution fields such as `git_commit_id`. Values may differ from `tool_result` for an accepted call if the permission decision rewrites the tool input via `updatedInput`. Use this attribute to see which command was rejected when `decision` is `"reject"`. + * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox` + * For WorkspaceBash tool: includes `bash_command`, `full_command`, `timeout` + * For MCP tools: includes `mcp_server_name`, `mcp_tool_name` + * For Skill tool: includes `skill_name` + * For Agent tool or legacy Task tool: includes `subagent_type` #### @@ -1112,9 +1119,13 @@ ---|--- `mcp_server_connection`| Server connect, disconnect, and connection failure with `server_name`, `transport_type`, `server_scope`, and error detail `tool_result`| Each MCP tool call with `tool_name` and `mcp_server_scope`, a `tool_parameters` payload containing `mcp_server_name` and `mcp_tool_name`, and a `tool_input` payload containing the call arguments -`tool_decision`| Whether the call was allowed or denied, and whether the decision came from config, a hook, or the user - -Without `OTEL_LOG_TOOL_DETAILS`, `tool_result` events still carry `tool_name` and `mcp_server_scope` but omit the `mcp_server_name`/`mcp_tool_name` breakdown and the arguments, and `mcp_server_connection` events omit `server_name` and the error message. +`tool_decision`| Whether the call was allowed or denied, whether the decision came from config, a hook, or the user, and a `tool_parameters` payload containing `mcp_server_name` and `mcp_tool_name` + +Without `OTEL_LOG_TOOL_DETAILS`, these events drop the identifying detail: + + * `tool_result`: keeps `tool_name` and `mcp_server_scope`, omits `mcp_server_name`, `mcp_tool_name`, and arguments + * `tool_decision`: keeps `tool_name`, omits `tool_parameters` + * `mcp_server_connection`: omits `server_name` and the error message ### @@ -1126,13 +1137,13 @@ Signal| Event| Key attributes ---|---|--- -Tool call allowed or denied, and by what| `tool_decision`| `decision`, `source`, `tool_name` +Tool call allowed or denied, and by what| `tool_decision`| `decision`, `source`, `tool_name`, `tool_parameters` Permission mode escalation| `permission_mode_changed`| `from_mode`, `to_mode`, `trigger` Policy hook blocked an action| `hook_execution_complete`| `hook_event`, `num_blocking` Login, logout, and authentication failure| `auth`| `action`, `success`, `error_category` MCP server connect or failure| `mcp_server_connection`| `status`, `server_name`, `error_code` Plugin installed and its source| `plugin_installed`| `plugin.name`, `marketplace.name`, `marketplace.is_official` -Commands run and files touched| `tool_result` with `OTEL_LOG_TOOL_DETAILS=1`| `tool_parameters`, `tool_input` +Commands run and files touched| `tool_result` (executed) or `tool_decision` (rejected) with `OTEL_LOG_TOOL_DETAILS=1`| `tool_parameters`; `tool_input` (`tool_result` only) Claude Code emits the raw event stream only. Anomaly detection, baselining, correlation across sessions, and alerting are the responsibility of your SIEM or observability backend. @@ -1230,7 +1241,11 @@ * Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` - * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names, plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. `user_prompt` events include the verbatim `command_name` for custom, plugin, and MCP commands. Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed + * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. This data is sent only to the OTEL endpoint you configure, never to Anthropic. Arguments may still contain sensitive values, so configure your telemetry backend to filter or redact these attributes as needed. When enabled: + * `tool_result` and `tool_decision` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names. Fields such as `full_command` are emitted untruncated + * `tool_result` events additionally include a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters + * `user_prompt` events include the verbatim `command_name` for custom, plugin, and MCP commands + * Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`, with the same truncation as `tool_input` * Tool input and output content is not logged in trace spans by default. To include it, set `OTEL_LOG_TOOL_CONTENT=1`. When enabled, span events include full tool input and output content truncated at 60 KB per span. This can include raw file contents from Read tool results and Bash command output. Configure your telemetry backend to filter or redact these attributes as needed * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES`. With `=1`, each API call emits `api_request_body` and `api_response_body` log events whose `body` attribute is the JSON-serialized payload, truncated at 60 KB. With `=file:<dir>`, untruncated bodies are written to `.request.json` and `.response.json` files under that directory and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. In both modes, bodies contain the full conversation history (system prompt, every prior user and assistant turn, tool results), so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude’s extended-thinking content is always redacted from these bodies regardless of other settings
modified
Show diff (126 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -123,6 +123,7 @@ `OTEL_METRICS_INCLUDE_SESSION_ID`| Include session.id attribute in metrics| `true`| `false` `OTEL_METRICS_INCLUDE_VERSION`| Include app.version attribute in metrics| `false`| `true` `OTEL_METRICS_INCLUDE_ACCOUNT_UUID`| Include user.account_uuid and user.account_id attributes in metrics| `true`| `false` +`OTEL_METRICS_INCLUDE_ENTRYPOINT`| Include app.entrypoint attribute in metrics| `false`| `true` These variables help control the cardinality of metrics, which affects storage requirements and query performance in your metrics backend. Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. @@ -142,7 +143,7 @@ `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`| OTLP traces endpoint, overrides `OTEL_EXPORTER_OTLP_ENDPOINT`| `http://localhost:4318/v1/traces` `OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000` -Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. When tracing is active and Claude Code is connected directly to the Anthropic API, each model request carries a W3C `traceparent` header set to the `claude_code.llm_request` span’s context, and the API’s `traceresponse` header is recorded as a span link. Together these connect Claude Code’s client-side spans to the server-side trace through any compliant intermediary. The header is not sent to third-party providers. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. +Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. When tracing is active and Claude Code is connected directly to the Anthropic API, each model request carries a W3C `traceparent` header set to the `claude_code.llm_request` span’s context, and the API’s `traceresponse` header is recorded as a span link. Together these connect Claude Code’s client-side spans to the server-side trace through any compliant intermediary. Outbound HTTP MCP requests carry `traceparent` the same way. The header is not sent to third-party providers. By default, the `traceparent` header on model and HTTP MCP requests is sent only when `ANTHROPIC_BASE_URL` is unset or points at the Anthropic API, since some proxies reject unrecognized headers. The subprocess `TRACEPARENT` variable is controlled by the same switch for consistency. If you run Claude Code through a custom `ANTHROPIC_BASE_URL` proxy and want trace context propagated, set `CLAUDE_CODE_PROPAGATE_TRACEPARENT=1`. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. #### @@ -272,6 +273,8 @@ "otelHeadersHelper": "/bin/generate_opentelemetry_headers.sh" } +The value can be the path to an executable file, including a path that contains spaces, or a shell command line with arguments. On Windows, the value always runs through the shell, so quote a path that contains spaces inside the JSON value. + #### ​ @@ -283,6 +286,12 @@ #!/bin/bash # Example: Multiple headers echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}" + +If the helper fails or prints output that doesn’t meet these requirements, Claude Code reports the error in: + + * `/doctor` output + * The debug log, when running with [`--debug`](</docs/en/cli-reference#cli-flags>) or after running `/debug` in the session + * stderr, in non-interactive sessions started with `-p` #### @@ -398,6 +407,7 @@ ---|---|--- `session.id`| Unique session identifier| `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) `app.version`| Current Claude Code version| `OTEL_METRICS_INCLUDE_VERSION` (default: false) +`app.entrypoint`| How the session was launched, such as `cli`, `sdk-cli`, `sdk-ts`, `sdk-py`, or `claude-vscode`| `OTEL_METRICS_INCLUDE_ENTRYPOINT` (default: false) `organization.id`| Organization UUID (when authenticated)| Always included when available `user.account_uuid`| Account UUID (when authenticated)| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) `user.account_id`| Account ID in tagged format matching Anthropic admin APIs (when authenticated), such as `user_01BWBeN28...`| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) @@ -496,6 +506,8 @@ * `skill.name`: Skill active for the request, set by the Skill tool, a `/` command, or inherited by a spawned subagent. Built-in, bundled, user-defined, and official-marketplace plugin skill names appear verbatim. Third-party plugin skill names are replaced with `"third-party"`. Absent when no skill is active. * `plugin.name`: Owning plugin when the active skill or subagent is provided by a plugin. Official-marketplace plugin names appear verbatim. Third-party plugin names are replaced with `"third-party"`. Absent when neither the skill nor the subagent has an owning plugin. * `marketplace.name`: Marketplace the owning plugin was installed from. Only emitted for official-marketplace plugins. Absent otherwise. + * `mcp_server.name`: MCP server whose tool ran in the turn that produced this request. Built-in, claude.ai-proxied, and official-registry server names appear verbatim. User-configured server names are replaced with `"custom"`. Absent when no MCP tool ran. + * `mcp_tool.name`: MCP tool that ran in the turn that produced this request, with the same redaction as `mcp_server.name`. Absent when no MCP tool ran. #### @@ -511,7 +523,7 @@ * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. See Cost counter for details. - * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`: Skill, plugin, and agent attribution for the request. See Cost counter for definitions and redaction behavior. + * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. #### @@ -585,7 +597,7 @@ Tool result event -Logged when a tool completes execution. **Event Name** : `claude_code.tool_result` **Attributes** : +Logged when a tool completes execution. Not emitted if the tool call was rejected; see the Tool decision event for rejections. **Event Name** : `claude_code.tool_result` **Attributes** : * All standard attributes * `event.name`: `"tool_result"` @@ -597,8 +609,8 @@ * `duration_ms`: Execution time in milliseconds * `error_type`: Error category string when the tool failed, such as `"Error:ENOENT"` or `"ShellError"` * `error` (when `OTEL_LOG_TOOL_DETAILS=1`): Full error message when the tool failed - * `decision_type`: Either `"accept"` or `"reject"` - * `decision_source`: Where the decision came from. One of `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`. See the Tool decision event for what each value means. + * `decision_type`: Always `"accept"`, since this event is only emitted after the tool runs (rejected calls don’t produce a tool result) + * `decision_source`: Where the permission decision came from. One of `"config"`, `"hook"`, `"user_permanent"`, or `"user_temporary"`. See the Tool decision event for what each value means. The reject-only sources `"user_abort"` and `"user_reject"` never appear on this event. * `tool_input_size_bytes`: Size of the JSON-serialized tool input in bytes * `tool_result_size_bytes`: Size of the tool result in bytes * `mcp_server_scope`: MCP server scope identifier (for MCP tools) @@ -632,6 +644,7 @@ * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model does not support effort. + * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. #### @@ -654,6 +667,7 @@ * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when the model does not support effort. + * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. #### @@ -710,12 +724,12 @@ * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. * `decision`: Either `"accept"` or `"reject"` * `source`: Where the decision came from: - * `"config"`: Decided automatically without prompting, based on project settings, allow rules in the user’s personal settings, enterprise managed policy, `--allowedTools` or `--disallowedTools` flags, the active permission mode, a session-scoped grant from an earlier prompt in the same interactive CLI session, or because the tool is inherently safe. The event does not indicate which of these sources matched. + * `"config"`: Decided automatically without prompting, based on project settings, allow or deny rules in the user’s personal settings, enterprise managed policy, `--allowedTools` or `--disallowedTools` flags, the active permission mode, a session-scoped grant from an earlier prompt in the same interactive CLI session, or because the tool is inherently safe. The event does not indicate which of these sources matched. * `"hook"`: A `PreToolUse` or `PermissionRequest` hook returned the decision. * `"user_permanent"`: Emitted when the user chose “Yes, and don’t ask again for …” at a permission prompt, which saves an allow rule to their personal settings. In the interactive CLI this is emitted only for that choice itself; later calls that match the saved rule emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the initial choice and later rule matches emit `"user_permanent"`. Treated as an accept. * `"user_temporary"`: Emitted when the user chose “Yes” at a permission prompt for a one-time approval, or chose one of the ”… during this session” options on a file edit or read prompt. In the interactive CLI this is emitted only for the choice itself; later calls allowed by that session-scoped grant emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the choice and later matches emit `"user_temporary"`. Treated as an accept. * `"user_abort"`: Emitted when the user dismissed the permission prompt without answering. Treated as a reject. - * `"user_reject"`: Emitted when the user chose “No” when prompted, or a call matched a deny rule in their personal settings. Treated as a reject. + * `"user_reject"`: Emitted when the user chose “No” when prompted. In the interactive CLI this is emitted only for that choice itself; calls that match a deny rule in the user’s personal settings emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, calls that match a deny rule in personal settings emit `"user_reject"`. Treated as a reject. #### @@ -976,6 +990,7 @@ * `pre_tokens`: Approximate token count before compaction * `post_tokens`: Approximate token count after compaction * `error`: Error message when compaction failed + * `precompute_reuse`: Only set when `trigger` is `"manual"`. Auto-compaction can prepare a summary in the background before the context window fills, and this attribute records whether `/compact` reused that prepared summary. `"hit"` means it was reused; `"miss_custom_instructions"`, `"miss_hook"`, and `"miss_not_ready"` give the reason a fresh summary was computed instead. Requires Claude Code v2.1.153 or later ####
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -142,7 +142,7 @@ `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`| OTLP traces endpoint, overrides `OTEL_EXPORTER_OTLP_ENDPOINT`| `http://localhost:4318/v1/traces` `OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000` -Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. +Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. When tracing is active and Claude Code is connected directly to the Anthropic API, each model request carries a W3C `traceparent` header set to the `claude_code.llm_request` span’s context, and the API’s `traceresponse` header is recorded as a span link. Together these connect Claude Code’s client-side spans to the server-side trace through any compliant intermediary. The header is not sent to third-party providers. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. #### @@ -213,6 +213,8 @@ `tool_name`| Tool name| `duration_ms`| Wall-clock duration including permission wait and execution| `result_tokens`| Approximate token size of the tool result| +`agent_id`| Identifier of the subagent or teammate that ran the tool. Absent on the main session| +`parent_agent_id`| Identifier of the agent that spawned this one. Absent for the main session and for agents spawned directly from it| `file_path`| Target file path for Read, Edit, and Write tools| `OTEL_LOG_TOOL_DETAILS` `full_command`| Command string for the Bash tool| `OTEL_LOG_TOOL_DETAILS` `skill_name`| Skill name for the Skill tool| `OTEL_LOG_TOOL_DETAILS` @@ -944,6 +946,22 @@ ​ +Hook plugin metrics event + +Logged when an official-marketplace plugin hook emits per-invocation metrics. Only plugins installed from an official Anthropic marketplace can emit these. Third-party marketplace plugins and user-configured hooks do not emit to this event. Use this event to monitor plugin behavior such as finding rates, costs, and durations from your own observability stack. **Event Name** : `claude_code.hook_plugin_metrics` **Attributes** : + + * All standard attributes + * `event.name`: `"hook_plugin_metrics"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `plugin_id`: plugin identifier in `<name>@<marketplace>` form + * `hook_event`: hook event type that emitted the metrics + * Up to 20 plugin-emitted metric keys. Names match `^[a-z][a-z0-9_]{0,39}$`. Values are boolean or number. + +#### + +​ + Compaction event Logged when conversation compaction completes. **Event Name** : `claude_code.compaction` **Attributes** :
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -959,6 +959,24 @@ * `post_tokens`: Approximate token count after compaction * `error`: Error message when compaction failed +#### + +​ + +Feedback survey event + +Logged when a session quality survey is shown or answered. See [Session quality surveys](</docs/en/data-usage#session-quality-surveys>) for what the surveys collect and how to control them. **Event Name** : `claude_code.feedback_survey` **Attributes** : + + * All standard attributes + * `event.name`: `"feedback_survey"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `event_type`: Survey lifecycle event, for example `"appeared"`, `"responded"`, or `"transcript_prompt_appeared"` + * `appearance_id`: Unique ID linking the events emitted for one survey instance + * `survey_type`: Which survey produced the event. `"session"` is the “How is Claude doing?” rating prompt + * `response`: The user’s selection on `responded` events + * `enabled_via_override`: `true` when [`CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL`](</docs/en/env-vars>) is set. Emitted as a boolean, not a string. Present on `session` survey events. Filter on this attribute to confirm the override is applied across a fleet + ## ​
modified
Show diff (104 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -185,6 +185,8 @@ `gen_ai.system`| Always `anthropic`. OpenTelemetry GenAI semantic convention| `gen_ai.request.model`| Same value as `model`. OpenTelemetry GenAI semantic convention| `query_source`| Subsystem that issued the request, such as `repl_main_thread` or a subagent name| +`agent_id`| Identifier of the subagent or teammate that issued the request. Absent on the main session| +`parent_agent_id`| Identifier of the agent that spawned this one. Absent for the main session and for agents spawned directly from it| `speed`| `fast` or `normal`| `llm_request.context`| `interaction`, `tool`, or `standalone` depending on the parent span| `duration_ms`| Wall-clock duration including retries| @@ -488,6 +490,10 @@ * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model does not support effort. + * `agent.name`: Subagent type that issued the request. Built-in agent names and agents from official-marketplace plugins appear verbatim. Other user-defined agent names are replaced with `"custom"`. Absent when the request was not issued by a named subagent type. + * `skill.name`: Skill active for the request, set by the Skill tool, a `/` command, or inherited by a spawned subagent. Built-in, bundled, user-defined, and official-marketplace plugin skill names appear verbatim. Third-party plugin skill names are replaced with `"third-party"`. Absent when no skill is active. + * `plugin.name`: Owning plugin when the active skill or subagent is provided by a plugin. Official-marketplace plugin names appear verbatim. Third-party plugin names are replaced with `"third-party"`. Absent when neither the skill nor the subagent has an owning plugin. + * `marketplace.name`: Marketplace the owning plugin was installed from. Only emitted for official-marketplace plugins. Absent otherwise. #### @@ -503,6 +509,7 @@ * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. See Cost counter for details. + * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`: Skill, plugin, and agent attribution for the request. See Cost counter for definitions and redaction behavior. #### @@ -799,6 +806,30 @@ ​ +Plugin loaded event + +Logged once per enabled plugin at session start. Use this event to inventory which plugins are active across your fleet, as a complement to `plugin_installed` which records the install action itself. **Event Name** : `claude_code.plugin_loaded` **Attributes** : + + * All standard attributes + * `event.name`: `"plugin_loaded"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `plugin.name`: name of the plugin. For plugins outside the official marketplace and built-in bundle the value is `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` + * `marketplace.name`: marketplace the plugin was installed from, when known. Redacted to `"third-party"` under the same condition as `plugin.name` + * `plugin.version`: version from the plugin manifest. Included only when the name is not redacted and the manifest declares a version + * `plugin.scope`: provenance category for the plugin: `"official"`, `"org"`, `"user-local"`, or `"default-bundle"` + * `enabled_via`: how the plugin came to be enabled: `"default-enable"`, `"org-policy"`, `"seed-mount"`, or `"user-install"` + * `plugin_id_hash`: deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count how many distinct third-party plugins are loaded across your fleet without recording their names + * `has_hooks`: whether the plugin contributes hooks + * `has_mcp`: whether the plugin contributes MCP servers + * `skill_path_count`: number of skill directories the plugin declares + * `command_path_count`: number of command directories the plugin declares + * `agent_path_count`: number of agent directories the plugin declares + +#### + +​ + Skill activated event Logged when a skill is invoked, whether Claude calls it through the Skill tool or you run it as a `/` command. **Event Name** : `claude_code.skill_activated` **Attributes** : @@ -846,6 +877,25 @@ * `total_attempts`: Total number of attempts made * `total_retry_duration_ms`: Total wall-clock time across all attempts * `speed`: `"fast"` or `"normal"` + +#### + +​ + +Hook registered event + +Logged once per configured hook at session start. Use this event to inventory which hooks are active across your fleet, as a complement to the per-execution `hook_execution_start` and `hook_execution_complete` events. **Event Name** : `claude_code.hook_registered` **Attributes** : + + * All standard attributes + * `event.name`: `"hook_registered"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `hook_event`: hook event type, such as `"PreToolUse"` or `"PostToolUse"` + * `hook_type`: hook implementation type: `"command"`, `"prompt"`, `"mcp_tool"`, `"http"`, or `"agent"` + * `hook_source`: where the hook is defined: `"userSettings"`, `"projectSettings"`, `"localSettings"`, `"flagSettings"`, `"policySettings"`, or `"pluginHook"` + * `hook_matcher` (when `OTEL_LOG_TOOL_DETAILS=1`): the matcher string from the hook configuration, when one is set + * `plugin.name` (when `hook_source` is `"pluginHook"`): name of the contributing plugin. For plugins outside the official marketplace and built-in bundle the value is `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` + * `plugin_id_hash` (when `hook_source` is `"pluginHook"`): deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count distinct contributing plugins without recording their names #### @@ -925,7 +975,7 @@ Metric| Analysis Opportunity ---|--- -`claude_code.token.usage`| Break down by `type` (input/output), user, team, or model +`claude_code.token.usage`| Break down by `type` (input/output), user, team, model, `skill.name`, `plugin.name`, or `agent.name` `claude_code.session.count`| Track adoption and engagement over time `claude_code.lines_of_code.count`| Measure productivity by tracking code additions/removals `claude_code.commit.count` & `claude_code.pull_request.count`| Understand impact on development workflows @@ -940,6 +990,7 @@ * Tracking usage trends across teams or individuals * Identifying high-usage sessions for optimization + * Attributing spend to specific skills, plugins, or subagent types via the `skill.name`, `plugin.name`, and `agent.name` attributes Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, Amazon Bedrock, or Google Cloud Vertex).
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -701,10 +701,10 @@ * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. * `decision`: Either `"accept"` or `"reject"` * `source`: Where the decision came from: - * `"config"`: Decided automatically without prompting, based on project settings, enterprise managed policy, `--allowedTools` or `--disallowedTools` flags, the active permission mode, or because the tool is inherently safe. + * `"config"`: Decided automatically without prompting, based on project settings, allow rules in the user’s personal settings, enterprise managed policy, `--allowedTools` or `--disallowedTools` flags, the active permission mode, a session-scoped grant from an earlier prompt in the same interactive CLI session, or because the tool is inherently safe. The event does not indicate which of these sources matched. * `"hook"`: A `PreToolUse` or `PermissionRequest` hook returned the decision. - * `"user_permanent"`: Emitted when the user chose “Always allow” when prompted, saving a rule to their personal settings. Also emitted for later calls that match that saved rule. Treated as an accept. - * `"user_temporary"`: Emitted when the user chose “Yes” or “Yes, for this session” when prompted, without saving a rule. Also emitted for later calls in the same session that match that session-scoped allow. Treated as an accept. + * `"user_permanent"`: Emitted when the user chose “Yes, and don’t ask again for …” at a permission prompt, which saves an allow rule to their personal settings. In the interactive CLI this is emitted only for that choice itself; later calls that match the saved rule emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the initial choice and later rule matches emit `"user_permanent"`. Treated as an accept. + * `"user_temporary"`: Emitted when the user chose “Yes” at a permission prompt for a one-time approval, or chose one of the ”… during this session” options on a file edit or read prompt. In the interactive CLI this is emitted only for the choice itself; later calls allowed by that session-scoped grant emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the choice and later matches emit `"user_temporary"`. Treated as an accept. * `"user_abort"`: Emitted when the user dismissed the permission prompt without answering. Treated as a reject. * `"user_reject"`: Emitted when the user chose “No” when prompted, or a call matched a deny rule in their personal settings. Treated as a reject.
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -461,7 +461,7 @@ Pull request counter -Incremented when creating pull requests via Claude Code. **Attributes** : +Incremented when Claude Code creates a pull request or merge request through a shell command or an MCP tool. **Attributes** : * All standard attributes
modified
Show diff (140 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -59,6 +59,8 @@ } Managed settings can be distributed via MDM (Mobile Device Management) or other device management solutions. Environment variables defined in the managed settings file have high precedence and cannot be overridden by users. + +Claude Code does not pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool does not inherit Claude Code’s exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry. ## @@ -84,8 +86,6 @@ `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL`| Protocol for logs, overrides general setting| `grpc`, `http/json`, `http/protobuf` `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`| OTLP logs endpoint, overrides general setting| `http://localhost:4318/v1/logs` `OTEL_EXPORTER_OTLP_HEADERS`| Authentication headers for OTLP| `Authorization=Bearer token` -`OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY`| Client key for mTLS authentication| Path to client key file -`OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE`| Client certificate for mTLS authentication| Path to client cert file `OTEL_METRIC_EXPORT_INTERVAL`| Export interval in milliseconds (default: 60000)| `5000`, `60000` `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable @@ -99,6 +99,21 @@ ​ +mTLS authentication + +How you configure client certificates for the OTLP exporter depends on the OTLP protocol in use for that signal, set via `OTEL_EXPORTER_OTLP_PROTOCOL` or the per-signal override. The same configuration applies to metrics, logs, and traces. + +Protocol| Client certificate variables| Trust the collector’s CA with +---|---|--- +`http/protobuf`, `http/json`| `CLAUDE_CODE_CLIENT_CERT`, `CLAUDE_CODE_CLIENT_KEY`, and optionally `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE`. See [Network configuration](</docs/en/network-config#mtls-authentication>)| `NODE_EXTRA_CA_CERTS` +`grpc`| `OTEL_EXPORTER_OTLP_CLIENT_KEY` and `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`, or the per-signal variants such as `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` to use a different certificate per signal| `OTEL_EXPORTER_OTLP_CERTIFICATE` + +For `grpc`, the OpenTelemetry SDK reads the standard OTLP variables directly, so existing configurations that set the per-signal metrics variables continue to work. + +### + +​ + Metrics cardinality control The following environment variables control which attributes are included in metrics to manage cardinality: @@ -117,7 +132,7 @@ Traces (beta) -Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend. Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the common OTLP configuration for endpoint, protocol, and headers. +Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend. Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the common OTLP configuration for endpoint, protocol, headers, and mTLS. Environment Variable| Description| Example Values ---|---|--- @@ -239,7 +254,7 @@ Dynamic headers -For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically: +For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically. Dynamic headers apply only to the `http/protobuf` and `http/json` protocols. The `grpc` exporter uses only the static `OTEL_EXPORTER_OTLP_HEADERS` value. #### @@ -969,6 +984,79 @@ ​ +Audit security events + +OpenTelemetry events are the audit data source for Claude Code activity. Every event carries identity attributes that tie tool calls, MCP activity, and permission decisions back to the user who triggered them, and the OTLP logs exporter can deliver these events to any Security Information and Event Management (SIEM) platform with an OTLP receiver or to an OpenTelemetry Collector that forwards to your SIEM. + +### + +​ + +Attribute actions to users + +The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account, plus the installation-scoped `user.id` and the per-session `session.id`. MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code does not act under a separate service account; the identity recorded on each event is the developer’s own Claude account. When Claude Code authenticates with a direct API key, or against Bedrock, Vertex AI, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper: + + export OTEL_RESOURCE_ATTRIBUTES="enduser.id=jdoe@example.com,enduser.directory_id=S-1-5-21-..." + +### + +​ + +Audit MCP activity + +To capture MCP server activity with full call detail, enable the logs exporter and set `OTEL_LOG_TOOL_DETAILS=1`. Each MCP operation then produces structured events that carry the server name, tool name, and call arguments alongside the standard identity attributes: + +Event| What it records for MCP +---|--- +`mcp_server_connection`| Server connect, disconnect, and connection failure with `server_name`, `transport_type`, `server_scope`, and error detail +`tool_result`| Each MCP tool call with `tool_name` and `mcp_server_scope`, a `tool_parameters` payload containing `mcp_server_name` and `mcp_tool_name`, and a `tool_input` payload containing the call arguments +`tool_decision`| Whether the call was allowed or denied, and whether the decision came from config, a hook, or the user + +Without `OTEL_LOG_TOOL_DETAILS`, `tool_result` events still carry `tool_name` and `mcp_server_scope` but omit the `mcp_server_name`/`mcp_tool_name` breakdown and the arguments, and `mcp_server_connection` events omit `server_name` and the error message. + +### + +​ + +Map security questions to events + +When building detection rules, look up the signal you want to monitor and query your backend for the corresponding event and attributes: + +Signal| Event| Key attributes +---|---|--- +Tool call allowed or denied, and by what| `tool_decision`| `decision`, `source`, `tool_name` +Permission mode escalation| `permission_mode_changed`| `from_mode`, `to_mode`, `trigger` +Policy hook blocked an action| `hook_execution_complete`| `hook_event`, `num_blocking` +Login, logout, and authentication failure| `auth`| `action`, `success`, `error_category` +MCP server connect or failure| `mcp_server_connection`| `status`, `server_name`, `error_code` +Plugin installed and its source| `plugin_installed`| `plugin.name`, `marketplace.name`, `marketplace.is_official` +Commands run and files touched| `tool_result` with `OTEL_LOG_TOOL_DETAILS=1`| `tool_parameters`, `tool_input` + +Claude Code emits the raw event stream only. Anomaly detection, baselining, correlation across sessions, and alerting are the responsibility of your SIEM or observability backend. + +### + +​ + +Send events to a SIEM + +Point `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` at your SIEM’s OTLP receiver, or at an OpenTelemetry Collector that forwards to your SIEM’s native ingest API. The following managed-settings example exports events only, with full tool detail enabled for MCP and Bash auditing: + + { + "env": { + "CLAUDE_CODE_ENABLE_TELEMETRY": "1", + "OTEL_LOGS_EXPORTER": "otlp", + "OTEL_LOG_TOOL_DETAILS": "1", + "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL": "http/protobuf", + "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT": "https://siem.example.com:4318/v1/logs", + "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer your-siem-token" + } + } + +## + +​ + Backend considerations Your choice of metrics, logs, and traces backends determines the types of analyses you can perform:
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -207,7 +207,7 @@ ---|---|--- `duration_ms`| Time spent waiting for the permission decision| `decision`| `accept` or `reject`| -`source`| Decision source, matching the `tool_decision` event| +`source`| Decision source, matching the Tool decision event| **`claude_code.tool.execution`** @@ -500,7 +500,7 @@ * All standard attributes * `tool_name`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`) * `decision`: User decision (`"accept"`, `"reject"`) - * `source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` + * `source`: Where the decision came from. One of `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`. See the Tool decision event for what each value means. * `language`: Programming language of the edited file, such as `"TypeScript"`, `"Python"`, `"JavaScript"`, or `"Markdown"`. Returns `"unknown"` for unrecognized file extensions. #### @@ -574,7 +574,7 @@ * `error_type`: Error category string when the tool failed, such as `"Error:ENOENT"` or `"ShellError"` * `error` (when `OTEL_LOG_TOOL_DETAILS=1`): Full error message when the tool failed * `decision_type`: Either `"accept"` or `"reject"` - * `decision_source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` + * `decision_source`: Where the decision came from. One of `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`. See the Tool decision event for what each value means. * `tool_input_size_bytes`: Size of the JSON-serialized tool input in bytes * `tool_result_size_bytes`: Size of the tool result in bytes * `mcp_server_scope`: MCP server scope identifier (for MCP tools) @@ -685,7 +685,13 @@ * `tool_name`: Name of the tool (for example, “Read”, “Edit”, “Write”, “NotebookEdit”) * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. * `decision`: Either `"accept"` or `"reject"` - * `source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` + * `source`: Where the decision came from: + * `"config"`: Decided automatically without prompting, based on project settings, enterprise managed policy, `--allowedTools` or `--disallowedTools` flags, the active permission mode, or because the tool is inherently safe. + * `"hook"`: A `PreToolUse` or `PermissionRequest` hook returned the decision. + * `"user_permanent"`: Emitted when the user chose “Always allow” when prompted, saving a rule to their personal settings. Also emitted for later calls that match that saved rule. Treated as an accept. + * `"user_temporary"`: Emitted when the user chose “Yes” or “Yes, for this session” when prompted, without saving a rule. Also emitted for later calls in the same session that match that session-scoped allow. Treated as an accept. + * `"user_abort"`: Emitted when the user dismissed the permission prompt without answering. Treated as a reject. + * `"user_reject"`: Emitted when the user chose “No” when prompted, or a call matched a deny rule in their personal settings. Treated as a reject. ####
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -920,7 +920,7 @@ * Tracking usage trends across teams or individuals * Identifying high-usage sessions for optimization -Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex). +Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, Amazon Bedrock, or Google Cloud Vertex). ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -780,13 +780,14 @@ Skill activated event -Logged when a skill is invoked. **Event Name** : `claude_code.skill_activated` **Attributes** : +Logged when a skill is invoked, whether Claude calls it through the Skill tool or you run it as a `/` command. **Event Name** : `claude_code.skill_activated` **Attributes** : * All standard attributes * `event.name`: `"skill_activated"` * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session * `skill.name`: Name of the skill. For user-defined and third-party plugin skills the value is the placeholder `"custom_skill"` unless `OTEL_LOG_TOOL_DETAILS=1` + * `invocation_trigger`: How the skill was triggered (`"user-slash"`, `"claude-proactive"`, or `"nested-skill"`) * `skill.source`: Where the skill was loaded from (for example, `"bundled"`, `"userSettings"`, `"projectSettings"`, `"plugin"`) * `plugin.name` (when `OTEL_LOG_TOOL_DETAILS=1` or the plugin is from an official marketplace): Name of the owning plugin when the skill is provided by a plugin * `marketplace.name` (when `OTEL_LOG_TOOL_DETAILS=1` or the plugin is from an official marketplace): Marketplace the owning plugin was installed from, when the skill is provided by a plugin
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.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. + Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, events via the logs/events protocol, and optionally distributed traces via the traces protocol. Configure your metrics, logs, and traces backends to match your monitoring requirements. ## @@ -617,7 +623,7 @@ * `event.sequence`: monotonically increasing counter for ordering events within a session * `model`: Model used (for example, “claude-sonnet-4-6”) * `error`: Error message - * `status_code`: HTTP status code as a string, or `"undefined"` for non-HTTP errors + * `status_code`: HTTP status code as a number. Absent for non-HTTP errors such as connection failures. * `duration_ms`: Request duration in milliseconds * `attempt`: Total number of attempts made, including the initial request (`1` means no retries occurred) * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. @@ -789,6 +795,21 @@ ​ +At mention event + +Logged when Claude Code resolves an `@`-mention in a prompt. Not every mention emits an event: early-exit paths such as permission denials, oversized files, PDF reference attachments, and directory listing failures return without logging. **Event Name** : `claude_code.at_mention` **Attributes** : + + * All standard attributes + * `event.name`: `"at_mention"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `mention_type`: Type of mention (`"file"`, `"directory"`, `"agent"`, `"mcp_resource"`) + * `success`: Whether the mention resolved successfully (`"true"` or `"false"`) + +#### + +​ + API retries exhausted event Logged once when an API request fails after more than one attempt. Emitted alongside the final `api_error` event. **Event Name** : `claude_code.api_retries_exhausted` **Attributes** : @@ -799,7 +820,7 @@ * `event.sequence`: monotonically increasing counter for ordering events within a session * `model`: Model used * `error`: Final error message - * `status_code`: HTTP status code as a string + * `status_code`: HTTP status code as a number. Absent for non-HTTP errors. * `total_attempts`: Total number of attempts made * `total_retry_duration_ms`: Total wall-clock time across all attempts * `speed`: `"fast"` or `"normal"` @@ -1008,7 +1029,7 @@ Security and privacy - * Telemetry is opt-in and requires explicit configuration + * OpenTelemetry export to your backend is opt-in and requires explicit configuration. For Anthropic’s separate operational telemetry and how to disable it, see [Data usage](</docs/en/data-usage#telemetry-services>) * Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -180,6 +180,8 @@ `status_code`| HTTP status code when the request failed| `error`| Error message when the request failed| `response.has_tool_call`| `true` when the response contained tool-use blocks| +`stop_reason`| API response `stop_reason`, such as `end_turn`, `tool_use`, `max_tokens`, `stop_sequence`, `pause_turn`, or `refusal`| +`gen_ai.response.finish_reasons`| Same value as `stop_reason`, wrapped in a string array. OpenTelemetry GenAI semantic convention| Each retry attempt is also recorded as a `gen_ai.request.attempt` span event with `attempt` and `client_request_id` attributes. **`claude_code.tool`** @@ -223,7 +225,7 @@ `num_non_blocking_error`| Count of hooks that failed without blocking| `num_cancelled`| Count of hooks cancelled before completion| -Additional content-bearing attributes such as `new_context`, `system_prompt_preview`, `tool_input`, and `response.model_output` are emitted only when detailed beta tracing is active. They are not part of the stable span schema. +Additional content-bearing attributes such as `new_context`, `system_prompt_preview`, `user_system_prompt`, `tool_input`, and `response.model_output` are emitted only when detailed beta tracing is active. They are not part of the stable span schema. `user_system_prompt` additionally requires `OTEL_LOG_USER_PROMPTS=1`. It carries only the system prompt text you provide via the `systemPrompt` SDK option or `--system-prompt` and `--append-system-prompt` flags, truncated at 60 KB, and is emitted once per session rather than per request. ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -560,12 +560,14 @@ * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session * `tool_name`: Name of the tool + * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. * `success`: `"true"` or `"false"` * `duration_ms`: Execution time in milliseconds * `error_type`: Error category string when the tool failed, such as `"Error:ENOENT"` or `"ShellError"` * `error` (when `OTEL_LOG_TOOL_DETAILS=1`): Full error message when the tool failed * `decision_type`: Either `"accept"` or `"reject"` * `decision_source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` + * `tool_input_size_bytes`: Size of the JSON-serialized tool input in bytes * `tool_result_size_bytes`: Size of the tool result in bytes * `mcp_server_scope`: MCP server scope identifier (for MCP tools) * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters: @@ -673,6 +675,7 @@ * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session * `tool_name`: Name of the tool (for example, “Read”, “Edit”, “Write”, “NotebookEdit”) + * `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data. * `decision`: Either `"accept"` or `"reject"` * `source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -83,7 +83,7 @@ `OTEL_METRIC_EXPORT_INTERVAL`| Export interval in milliseconds (default: 60000)| `5000`, `60000` `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable -`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, and tool input (default: disabled)| `1` to enable +`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events (default: disabled)| `1` to enable `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool input and output content in span events (default: disabled). Requires tracing. Content is truncated at 60 KB| `1` to enable `OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). 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| `1` for inline bodies truncated at 60 KB, or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` @@ -464,6 +464,7 @@ * `model`: Model identifier (for example, “claude-sonnet-4-6”) * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model does not support effort. #### @@ -478,6 +479,7 @@ * `model`: Model identifier (for example, “claude-sonnet-4-6”) * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` * `speed`: `"fast"` when the request used fast mode. Absent otherwise + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. See Cost counter for details. #### @@ -542,6 +544,8 @@ * `event.sequence`: monotonically increasing counter for ordering events within a session * `prompt_length`: Length of the prompt * `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`) + * `command_name`: Command name when the prompt invokes one. Built-in and bundled command names such as `compact` or `debug` are emitted as-is; aliases such as `reset` emit as typed rather than the canonical name. Custom, plugin, and MCP command names collapse to `custom` or `mcp` unless `OTEL_LOG_TOOL_DETAILS=1` is set + * `command_source`: Origin of the command when present: `builtin`, `custom`, or `mcp`. Plugin-provided commands report as `custom` #### @@ -593,6 +597,7 @@ * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model does not support effort. #### @@ -614,6 +619,7 @@ * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name + * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when the model does not support effort. #### @@ -1001,7 +1007,7 @@ * Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` - * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names, plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed + * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names, plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. `user_prompt` events include the verbatim `command_name` for custom, plugin, and MCP commands. Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed * Tool input and output content is not logged in trace spans by default. To include it, set `OTEL_LOG_TOOL_CONTENT=1`. When enabled, span events include full tool input and output content truncated at 60 KB per span. This can include raw file contents from Read tool results and Bash command output. Configure your telemetry backend to filter or redact these attributes as needed * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES`. With `=1`, each API call emits `api_request_body` and `api_response_body` log events whose `body` attribute is the JSON-serialized payload, truncated at 60 KB. With `=file:<dir>`, untruncated bodies are written to `.request.json` and `.response.json` files under that directory and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. In both modes, bodies contain the full conversation history (system prompt, every prior user and assistant turn, tool results), so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude’s extended-thinking content is always redacted from these bodies regardless of other settings
modified
Show diff (417 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -85,7 +85,7 @@ `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable `OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, and tool input (default: disabled)| `1` to enable `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool input and output content in span events (default: disabled). Requires tracing. Content is truncated at 60 KB| `1` to enable -`OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). Bodies include the entire conversation history and are truncated at 60 KB. Enabling this implies consent to everything `OTEL_LOG_USER_PROMPTS`, `OTEL_LOG_TOOL_DETAILS`, and `OTEL_LOG_TOOL_CONTENT` would reveal| `1` to enable +`OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). 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| `1` for inline bodies truncated at 60 KB, or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes)| `900000` @@ -122,6 +122,108 @@ `OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000` Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. + +#### + +​ + +Span hierarchy + +Each user prompt starts a `claude_code.interaction` root span. API calls, tool calls, and hook executions are recorded as its children. Tool spans have two child spans of their own: one for the time spent waiting on a permission decision and one for the execution itself. When the Task tool spawns a subagent, the subagent’s API and tool spans nest under the parent’s `claude_code.tool` span. + + claude_code.interaction + ├── claude_code.llm_request + ├── claude_code.hook (requires detailed beta tracing) + └── claude_code.tool + ├── claude_code.tool.blocked_on_user + ├── claude_code.tool.execution + └── (Task tool) subagent claude_code.llm_request / claude_code.tool spans + +In Agent SDK and `claude -p` sessions, `claude_code.interaction` itself becomes a child of the caller’s span when `TRACEPARENT` is set in the environment. + +#### + +​ + +Span attributes + +Every span carries the standard attributes plus a `span.type` attribute matching its name. The tables below list the additional attributes set on each span. The `llm_request`, `tool.execution`, and `hook` spans set OpenTelemetry status `ERROR` when they record a failure; the other spans always end with status `UNSET`. **`claude_code.interaction`** + +Attribute| Description| Gated by +---|---|--- +`user_prompt`| Prompt text. Value is `<REDACTED>` unless the gate is set| `OTEL_LOG_USER_PROMPTS` +`user_prompt_length`| Prompt length in characters| +`interaction.sequence`| 1-based counter of interactions in this session| +`interaction.duration_ms`| Wall-clock duration of the turn| + +**`claude_code.llm_request`** + +Attribute| Description| Gated by +---|---|--- +`model`| Model identifier| +`gen_ai.system`| Always `anthropic`. OpenTelemetry GenAI semantic convention| +`gen_ai.request.model`| Same value as `model`. OpenTelemetry GenAI semantic convention| +`query_source`| Subsystem that issued the request, such as `repl_main_thread` or a subagent name| +`speed`| `fast` or `normal`| +`llm_request.context`| `interaction`, `tool`, or `standalone` depending on the parent span| +`duration_ms`| Wall-clock duration including retries| +`ttft_ms`| Time to first token in milliseconds| +`input_tokens`| Input token count from the API usage block| +`output_tokens`| Output token count| +`cache_read_tokens`| Tokens read from prompt cache| +`cache_creation_tokens`| Tokens written to prompt cache| +`request_id`| Anthropic API request ID from the `request-id` response header| +`gen_ai.response.id`| Same value as `request_id`. OpenTelemetry GenAI semantic convention| +`client_request_id`| Client-generated `x-client-request-id` of the final attempt| +`attempt`| Total attempts made for this request| +`success`| `true` or `false`| +`status_code`| HTTP status code when the request failed| +`error`| Error message when the request failed| +`response.has_tool_call`| `true` when the response contained tool-use blocks| + +Each retry attempt is also recorded as a `gen_ai.request.attempt` span event with `attempt` and `client_request_id` attributes. **`claude_code.tool`** + +Attribute| Description| Gated by +---|---|--- +`tool_name`| Tool name| +`duration_ms`| Wall-clock duration including permission wait and execution| +`result_tokens`| Approximate token size of the tool result| +`file_path`| Target file path for Read, Edit, and Write tools| `OTEL_LOG_TOOL_DETAILS` +`full_command`| Command string for the Bash tool| `OTEL_LOG_TOOL_DETAILS` +`skill_name`| Skill name for the Skill tool| `OTEL_LOG_TOOL_DETAILS` +`subagent_type`| Subagent type for the Task tool| `OTEL_LOG_TOOL_DETAILS` + +When `OTEL_LOG_TOOL_CONTENT=1`, this span also records a `tool.output` span event whose attributes contain the tool’s input and output bodies, truncated at 60 KB per attribute. **`claude_code.tool.blocked_on_user`** + +Attribute| Description| Gated by +---|---|--- +`duration_ms`| Time spent waiting for the permission decision| +`decision`| `accept` or `reject`| +`source`| Decision source, matching the `tool_decision` event| + +**`claude_code.tool.execution`** + +Attribute| Description| Gated by +---|---|--- +`duration_ms`| Time spent running the tool body| +`success`| `true` or `false`| +`error`| Error category string when execution failed, such as `Error:ENOENT` or `ShellError`. Contains the full error message instead when the gate is set| `OTEL_LOG_TOOL_DETAILS` + +**`claude_code.hook`** This span is emitted only when detailed beta tracing is active, which requires `ENABLE_BETA_TRACING_DETAILED=1` and `BETA_TRACING_ENDPOINT` in addition to the trace exporter configuration above. In interactive CLI sessions, this also requires your organization to be allowlisted for the feature. Agent SDK and non-interactive `-p` sessions are not gated. It is not emitted when only `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` is set. + +Attribute| Description| Gated by +---|---|--- +`hook_event`| Hook event type, such as `PreToolUse`| +`hook_name`| Full hook name, such as `PreToolUse:Write`| +`num_hooks`| Number of matching hook commands executed| +`hook_definitions`| JSON-serialized hook configuration| `OTEL_LOG_TOOL_DETAILS` +`duration_ms`| Wall-clock duration of all matching hooks| +`num_success`| Count of hooks that completed successfully| +`num_blocking`| Count of hooks that returned a blocking decision| +`num_non_blocking_error`| Count of hooks that failed without blocking| +`num_cancelled`| Count of hooks cancelled before completion| + +Additional content-bearing attributes such as `new_context`, `system_prompt_preview`, `tool_input`, and `response.model_output` are emitted only when detailed beta tracing is active. They are not part of the stable span schema. ### @@ -317,6 +419,7 @@ Incremented at the start of each session. **Attributes** : * All standard attributes + * `start_type`: How the session was started. One of `"fresh"`, `"resume"`, or `"continue"` #### @@ -359,6 +462,8 @@ * All standard attributes * `model`: Model identifier (for example, “claude-sonnet-4-6”) + * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` + * `speed`: `"fast"` when the request used fast mode. Absent otherwise #### @@ -371,6 +476,8 @@ * All standard attributes * `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`) * `model`: Model identifier (for example, “claude-sonnet-4-6”) + * `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"` + * `speed`: `"fast"` when the request used fast mode. Absent otherwise #### @@ -451,7 +558,8 @@ * `tool_name`: Name of the tool * `success`: `"true"` or `"false"` * `duration_ms`: Execution time in milliseconds - * `error`: Error message (if failed) + * `error_type`: Error category string when the tool failed, such as `"Error:ENOENT"` or `"ShellError"` + * `error` (when `OTEL_LOG_TOOL_DETAILS=1`): Full error message when the tool failed * `decision_type`: Either `"accept"` or `"reject"` * `decision_source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` * `tool_result_size_bytes`: Size of the tool result in bytes @@ -460,6 +568,7 @@ * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds) * For MCP tools: includes `mcp_server_name`, `mcp_tool_name` * For Skill tool: includes `skill_name` + * For Task tool: includes `subagent_type` * `tool_input` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON-serialized tool arguments. Individual values over 512 characters are truncated, and the full payload is bounded to ~4 K characters. Applies to all tools including MCP tools. #### @@ -483,6 +592,7 @@ * `cache_creation_tokens`: Number of tokens used for cache creation * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active + * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name #### @@ -503,6 +613,7 @@ * `attempt`: Total number of attempts made, including the initial request (`1` means no retries occurred) * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active + * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name #### @@ -510,15 +621,16 @@ API request body event -Logged for each API request attempt when `OTEL_LOG_RAW_API_BODIES=1`. One event is emitted per attempt, so retries with adjusted parameters each produce their own event. **Event Name** : `claude_code.api_request_body` **Attributes** : +Logged for each API request attempt when `OTEL_LOG_RAW_API_BODIES` is set. One event is emitted per attempt, so retries with adjusted parameters each produce their own event. **Event Name** : `claude_code.api_request_body` **Attributes** : * All standard attributes * `event.name`: `"api_request_body"` * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session - * `body`: JSON-serialized Messages API request parameters (system prompt, messages, tools, etc.), truncated at 60 KB. Extended-thinking content in prior assistant turns is redacted. - * `body_length`: Original (pre-truncation) JSON length in characters - * `body_truncated`: `"true"` when truncation occurred (absent otherwise) + * `body`: JSON-serialized Messages API request parameters (system prompt, messages, tools, etc.), truncated at 60 KB. Extended-thinking content in prior assistant turns is redacted. Emitted only in inline mode (`OTEL_LOG_RAW_API_BODIES=1`). + * `body_ref`: Absolute path to a `<dir>/<uuid>.request.json` file containing the untruncated body. Emitted only in file mode (`OTEL_LOG_RAW_API_BODIES=file:<dir>`). + * `body_length`: Untruncated body length. UTF-8 bytes when `OTEL_LOG_RAW_API_BODIES=file:<dir>`, or UTF-16 code units when `=1` + * `body_truncated`: `"true"` when inline truncation occurred. Absent in file mode and when no truncation occurred. * `model`: Model identifier from the request parameters * `query_source`: Subsystem that issued the request (for example, `"compact"`) @@ -528,15 +640,16 @@ API response body event -Logged for each successful API response when `OTEL_LOG_RAW_API_BODIES=1`. **Event Name** : `claude_code.api_response_body` **Attributes** : +Logged for each successful API response when `OTEL_LOG_RAW_API_BODIES` is set. **Event Name** : `claude_code.api_response_body` **Attributes** : * All standard attributes * `event.name`: `"api_response_body"` * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session - * `body`: JSON-serialized Messages API response (id, content blocks, usage, stop reason), truncated at 60 KB. Extended-thinking content is redacted. - * `body_length`: Original (pre-truncation) JSON length in characters - * `body_truncated`: `"true"` when truncation occurred (absent otherwise) + * `body`: JSON-serialized Messages API response (id, content blocks, usage, stop reason), truncated at 60 KB. Extended-thinking content is redacted. Emitted only in inline mode (`OTEL_LOG_RAW_API_BODIES=1`). + * `body_ref`: Absolute path to a `<dir>/<request_id>.response.json` file containing the untruncated body. Emitted only in file mode (`OTEL_LOG_RAW_API_BODIES=file:<dir>`). + * `body_length`: Untruncated body length. UTF-8 bytes when `OTEL_LOG_RAW_API_BODIES=file:<dir>`, or UTF-16 code units when `=1` + * `body_truncated`: `"true"` when inline truncation occurred. Absent in file mode and when no truncation occurred. * `model`: Model identifier * `query_source`: Subsystem that issued the request * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. @@ -561,6 +674,75 @@ ​ +Permission mode changed event + +Logged when the permission mode changes, for example from `Shift+Tab` cycling, exiting plan mode, or an auto mode gate check. **Event Name** : `claude_code.permission_mode_changed` **Attributes** : + + * All standard attributes + * `event.name`: `"permission_mode_changed"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `from_mode`: The previous permission mode, for example `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, or `"bypassPermissions"` + * `to_mode`: The new permission mode + * `trigger`: What caused the change. One of `"shift_tab"`, `"exit_plan_mode"`, `"auto_gate_denied"`, or `"auto_opt_in"`. Absent when the transition originates from the SDK or bridge + +#### + +​ + +Auth event + +Logged when `/login` or `/logout` completes. **Event Name** : `claude_code.auth` **Attributes** : + + * All standard attributes + * `event.name`: `"auth"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `action`: `"login"` or `"logout"` + * `success`: `"true"` or `"false"` + * `auth_method`: Authentication method, such as `"oauth"` + * `error_category`: Categorical error kind when the action failed. The raw error message is never included + * `status_code`: HTTP status code as a string when the action failed with an HTTP error + +#### + +​ + +MCP server connection event + +Logged when an MCP server connects, disconnects, or fails to connect. **Event Name** : `claude_code.mcp_server_connection` **Attributes** : + + * All standard attributes + * `event.name`: `"mcp_server_connection"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `status`: `"connected"`, `"failed"`, or `"disconnected"` + * `transport_type`: Server transport, such as `"stdio"`, `"sse"`, or `"http"` + * `server_scope`: Scope the server is configured at, such as `"user"`, `"project"`, or `"local"` + * `duration_ms`: Connection attempt duration in milliseconds + * `error_code`: Error code when the connection failed + * `server_name` (when `OTEL_LOG_TOOL_DETAILS=1`): Configured server name + * `error` (when `OTEL_LOG_TOOL_DETAILS=1`): Full error message when the connection failed + +#### + +​ + +Internal error event + +Logged when Claude Code catches an unexpected internal error. Only the error class name and an errno-style code are recorded. The error message and stack trace are never included. This event is not emitted when running against Bedrock, Vertex, or Foundry, or when `DISABLE_ERROR_REPORTING` is set. **Event Name** : `claude_code.internal_error` **Attributes** : + + * All standard attributes + * `event.name`: `"internal_error"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `error_name`: Error class name, such as `"TypeError"` or `"SyntaxError"` + * `error_code`: Node.js errno code such as `"ENOENT"` when present on the error + +#### + +​ + Plugin installed event Logged when a plugin finishes installing, from both the `claude plugin install` CLI command and the interactive `/plugin` UI. **Event Name** : `claude_code.plugin_installed` **Attributes** : @@ -569,11 +751,11 @@ * `event.name`: `"plugin_installed"` * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session - * `plugin.name`: Name of the installed plugin - * `plugin.version`: Plugin version when declared in the marketplace entry - * `marketplace.name`: Marketplace the plugin was installed from * `marketplace.is_official`: `"true"` if the marketplace is an official Anthropic marketplace, `"false"` otherwise * `install.trigger`: `"cli"` or `"ui"` + * `plugin.name`: Name of the installed plugin. For third-party marketplaces this is included only when `OTEL_LOG_TOOL_DETAILS=1` + * `plugin.version`: Plugin version when declared in the marketplace entry. For third-party marketplaces this is included only when `OTEL_LOG_TOOL_DETAILS=1` + * `marketplace.name`: Marketplace the plugin was installed from. For third-party marketplaces this is included only when `OTEL_LOG_TOOL_DETAILS=1` #### @@ -587,10 +769,91 @@ * `event.name`: `"skill_activated"` * `event.timestamp`: ISO 8601 timestamp * `event.sequence`: monotonically increasing counter for ordering events within a session - * `skill.name`: Name of the skill + * `skill.name`: Name of the skill. For user-defined and third-party plugin skills the value is the placeholder `"custom_skill"` unless `OTEL_LOG_TOOL_DETAILS=1` * `skill.source`: Where the skill was loaded from (for example, `"bundled"`, `"userSettings"`, `"projectSettings"`, `"plugin"`) - * `plugin.name`: Name of the owning plugin when the skill is provided by a plugin - * `marketplace.name`: Marketplace the owning plugin was installed from, when the skill is provided by a plugin + * `plugin.name` (when `OTEL_LOG_TOOL_DETAILS=1` or the plugin is from an official marketplace): Name of the owning plugin when the skill is provided by a plugin + * `marketplace.name` (when `OTEL_LOG_TOOL_DETAILS=1` or the plugin is from an official marketplace): Marketplace the owning plugin was installed from, when the skill is provided by a plugin + +#### + +​ + +API retries exhausted event + +Logged once when an API request fails after more than one attempt. Emitted alongside the final `api_error` event. **Event Name** : `claude_code.api_retries_exhausted` **Attributes** : + + * All standard attributes + * `event.name`: `"api_retries_exhausted"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `model`: Model used + * `error`: Final error message + * `status_code`: HTTP status code as a string + * `total_attempts`: Total number of attempts made + * `total_retry_duration_ms`: Total wall-clock time across all attempts + * `speed`: `"fast"` or `"normal"` + +#### + +​ + +Hook execution start event + +Logged when one or more hooks begin executing for a hook event. **Event Name** : `claude_code.hook_execution_start` **Attributes** : + + * All standard attributes + * `event.name`: `"hook_execution_start"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `hook_event`: Hook event type, such as `"PreToolUse"` or `"PostToolUse"` + * `hook_name`: Full hook name including matcher, such as `"PreToolUse:Write"` + * `num_hooks`: Number of matching hook commands + * `managed_only`: `"true"` when only managed-policy hooks are permitted + * `hook_source`: `"policySettings"` or `"merged"` + * `hook_definitions`: JSON-serialized hook configuration. Included only when both detailed beta tracing and `OTEL_LOG_TOOL_DETAILS=1` are enabled + +#### + +​ + +Hook execution complete event + +Logged when all hooks for a hook event have finished. **Event Name** : `claude_code.hook_execution_complete` **Attributes** : + + * All standard attributes + * `event.name`: `"hook_execution_complete"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `hook_event`: Hook event type + * `hook_name`: Full hook name including matcher + * `num_hooks`: Number of matching hook commands + * `num_success`: Count that completed successfully + * `num_blocking`: Count that returned a blocking decision + * `num_non_blocking_error`: Count that failed without blocking + * `num_cancelled`: Count cancelled before completion + * `total_duration_ms`: Wall-clock duration of all matching hooks + * `managed_only`: `"true"` when only managed-policy hooks are permitted + * `hook_source`: `"policySettings"` or `"merged"` + * `hook_definitions`: JSON-serialized hook configuration. Included only when both detailed beta tracing and `OTEL_LOG_TOOL_DETAILS=1` are enabled + +#### + +​ + +Compaction event + +Logged when conversation compaction completes. **Event Name** : `claude_code.compaction` **Attributes** : + + * All standard attributes + * `event.name`: `"compaction"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `trigger`: `"auto"` or `"manual"` + * `success`: `"true"` or `"false"` + * `duration_ms`: Compaction duration + * `pre_tokens`: Approximate token count before compaction + * `post_tokens`: Approximate token count after compaction + * `error`: Error message when compaction failed ## @@ -740,7 +1003,7 @@ * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names, plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed * Tool input and output content is not logged in trace spans by default. To include it, set `OTEL_LOG_TOOL_CONTENT=1`. When enabled, span events include full tool input and output content truncated at 60 KB per span. This can include raw file contents from Read tool results and Bash command output. Configure your telemetry backend to filter or redact these attributes as needed - * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES=1`. When enabled, each API call emits `api_request_body` and `api_response_body` log events whose `body` attribute is the JSON-serialized payload, truncated at 60 KB. These bodies contain the full conversation history (system prompt, every prior user and assistant turn, tool results), so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude’s extended-thinking content is always redacted from these bodies regardless of other settings + * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES`. With `=1`, each API call emits `api_request_body` and `api_response_body` log events whose `body` attribute is the JSON-serialized payload, truncated at 60 KB. With `=file:<dir>`, untruncated bodies are written to `.request.json` and `.response.json` files under that directory and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. In both modes, bodies contain the full conversation history (system prompt, every prior user and assistant turn, tool results), so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude’s extended-thinking content is always redacted from these bodies regardless of other settings ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -85,6 +85,7 @@ `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable `OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, and tool input (default: disabled)| `1` to enable `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool input and output content in span events (default: disabled). Requires tracing. Content is truncated at 60 KB| `1` to enable +`OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). Bodies include the entire conversation history and are truncated at 60 KB. Enabling this implies consent to everything `OTEL_LOG_USER_PROMPTS`, `OTEL_LOG_TOOL_DETAILS`, and `OTEL_LOG_TOOL_CONTENT` would reveal| `1` to enable `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes)| `900000` @@ -120,7 +121,7 @@ `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`| OTLP traces endpoint, overrides `OTEL_EXPORTER_OTLP_ENDPOINT`| `http://localhost:4318/v1/traces` `OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000` -Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. +Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. ### @@ -480,6 +481,7 @@ * `output_tokens`: Number of output tokens * `cache_read_tokens`: Number of tokens read from cache * `cache_creation_tokens`: Number of tokens used for cache creation + * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active #### @@ -499,7 +501,45 @@ * `status_code`: HTTP status code as a string, or `"undefined"` for non-HTTP errors * `duration_ms`: Request duration in milliseconds * `attempt`: Total number of attempts made, including the initial request (`1` means no retries occurred) + * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active + +#### + +​ + +API request body event + +Logged for each API request attempt when `OTEL_LOG_RAW_API_BODIES=1`. One event is emitted per attempt, so retries with adjusted parameters each produce their own event. **Event Name** : `claude_code.api_request_body` **Attributes** : + + * All standard attributes + * `event.name`: `"api_request_body"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `body`: JSON-serialized Messages API request parameters (system prompt, messages, tools, etc.), truncated at 60 KB. Extended-thinking content in prior assistant turns is redacted. + * `body_length`: Original (pre-truncation) JSON length in characters + * `body_truncated`: `"true"` when truncation occurred (absent otherwise) + * `model`: Model identifier from the request parameters + * `query_source`: Subsystem that issued the request (for example, `"compact"`) + +#### + +​ + +API response body event + +Logged for each successful API response when `OTEL_LOG_RAW_API_BODIES=1`. **Event Name** : `claude_code.api_response_body` **Attributes** : + + * All standard attributes + * `event.name`: `"api_response_body"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `body`: JSON-serialized Messages API response (id, content blocks, usage, stop reason), truncated at 60 KB. Extended-thinking content is redacted. + * `body_length`: Original (pre-truncation) JSON length in characters + * `body_truncated`: `"true"` when truncation occurred (absent otherwise) + * `model`: Model identifier + * `query_source`: Subsystem that issued the request + * `request_id`: Anthropic API request ID from the response’s `request-id` header, such as `"req_011..."`. Present only when the API returns one. #### @@ -700,6 +740,7 @@ * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names, plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed * Tool input and output content is not logged in trace spans by default. To include it, set `OTEL_LOG_TOOL_CONTENT=1`. When enabled, span events include full tool input and output content truncated at 60 KB per span. This can include raw file contents from Read tool results and Bash command output. Configure your telemetry backend to filter or redact these attributes as needed + * Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES=1`. When enabled, each API call emits `api_request_body` and `api_response_body` log events whose `body` attribute is the JSON-serialized payload, truncated at 60 KB. These bodies contain the full conversation history (system prompt, every prior user and assistant turn, tool results), so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude’s extended-thinking content is always redacted from these bodies regardless of other settings ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -83,7 +83,7 @@ `OTEL_METRIC_EXPORT_INTERVAL`| Export interval in milliseconds (default: 60000)| `5000`, `60000` `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable -`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events: Bash commands, MCP server and tool names, skill names, and tool input (default: disabled)| `1` to enable +`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, and tool input (default: disabled)| `1` to enable `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool input and output content in span events (default: disabled). Requires tracing. Content is truncated at 60 KB| `1` to enable `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes)| `900000` @@ -120,7 +120,7 @@ `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`| OTLP traces endpoint, overrides `OTEL_EXPORTER_OTLP_ENDPOINT`| `http://localhost:4318/v1/traces` `OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000` -Spans redact user prompt text and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1` and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. +Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. ### @@ -517,6 +517,41 @@ * `decision`: Either `"accept"` or `"reject"` * `source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` +#### + +​ + +Plugin installed event + +Logged when a plugin finishes installing, from both the `claude plugin install` CLI command and the interactive `/plugin` UI. **Event Name** : `claude_code.plugin_installed` **Attributes** : + + * All standard attributes + * `event.name`: `"plugin_installed"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `plugin.name`: Name of the installed plugin + * `plugin.version`: Plugin version when declared in the marketplace entry + * `marketplace.name`: Marketplace the plugin was installed from + * `marketplace.is_official`: `"true"` if the marketplace is an official Anthropic marketplace, `"false"` otherwise + * `install.trigger`: `"cli"` or `"ui"` + +#### + +​ + +Skill activated event + +Logged when a skill is invoked. **Event Name** : `claude_code.skill_activated` **Attributes** : + + * All standard attributes + * `event.name`: `"skill_activated"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `skill.name`: Name of the skill + * `skill.source`: Where the skill was loaded from (for example, `"bundled"`, `"userSettings"`, `"projectSettings"`, `"plugin"`) + * `plugin.name`: Name of the owning plugin when the skill is provided by a plugin + * `marketplace.name`: Marketplace the owning plugin was installed from, when the skill is provided by a plugin + ## ​ @@ -663,7 +698,7 @@ * Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` - * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names, plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed + * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names, plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed * Tool input and output content is not logged in trace spans by default. To include it, set `OTEL_LOG_TOOL_CONTENT=1`. When enabled, span events include full tool input and output content truncated at 60 KB per span. This can include raw file contents from Read tool results and Bash command output. Configure your telemetry backend to filter or redact these attributes as needed ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -120,7 +120,7 @@ `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`| OTLP traces endpoint, overrides `OTEL_EXPORTER_OTLP_ENDPOINT`| `http://localhost:4318/v1/traces` `OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000` -Spans redact user prompt text and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1` and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. +Spans redact user prompt text and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1` and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -498,7 +498,7 @@ * `error`: Error message * `status_code`: HTTP status code as a string, or `"undefined"` for non-HTTP errors * `duration_ms`: Request duration in milliseconds - * `attempt`: Attempt number (for retried requests) + * `attempt`: Total number of attempts made, including the initial request (`1` means no retries occurred) * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active #### @@ -564,6 +564,14 @@ * High session volume from specific users All metrics can be segmented by `user.account_uuid`, `user.account_id`, `organization.id`, `session.id`, `model`, and `app.version`. + +### + +​ + +Detect retry exhaustion + +Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records how many attempts were made in total. A value greater than `CLAUDE_CODE_MAX_RETRIES` (default `10`) indicates the request exhausted all retries on a transient error. A lower value indicates a non-retryable error such as a `400` response. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -120,7 +120,7 @@ `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`| OTLP traces endpoint, overrides `OTEL_EXPORTER_OTLP_ENDPOINT`| `http://localhost:4318/v1/traces` `OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000` -Spans redact user prompt text and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1` and `OTEL_LOG_TOOL_CONTENT=1` to include them. +Spans redact user prompt text and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1` and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. ###
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -1,4 +1,4 @@ -Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, and events via the logs/events protocol. Configure your metrics and logs backends to match your monitoring requirements. +Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, events via the logs/events protocol, and optionally distributed traces via the traces protocol. Configure your metrics, logs, and traces backends to match your monitoring requirements. ## @@ -84,6 +84,7 @@ `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable `OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events: Bash commands, MCP server and tool names, skill names, and tool input (default: disabled)| `1` to enable +`OTEL_LOG_TOOL_CONTENT`| Enable logging of tool input and output content in span events (default: disabled). Requires tracing. Content is truncated at 60 KB| `1` to enable `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes)| `900000` @@ -102,6 +103,24 @@ `OTEL_METRICS_INCLUDE_ACCOUNT_UUID`| Include user.account_uuid and user.account_id attributes in metrics| `true`| `false` These variables help control the cardinality of metrics, which affects storage requirements and query performance in your metrics backend. Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. + +### + +​ + +Traces (beta) + +Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend. Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the common OTLP configuration for endpoint, protocol, and headers. + +Environment Variable| Description| Example Values +---|---|--- +`CLAUDE_CODE_ENHANCED_TELEMETRY_BETA`| Enable span tracing (required). `ENABLE_ENHANCED_TELEMETRY_BETA` is also accepted| `1` +`OTEL_TRACES_EXPORTER`| Traces exporter types, comma-separated. Use `none` to disable| `console`, `otlp`, `none` +`OTEL_EXPORTER_OTLP_TRACES_PROTOCOL`| Protocol for traces, overrides `OTEL_EXPORTER_OTLP_PROTOCOL`| `grpc`, `http/json`, `http/protobuf` +`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`| OTLP traces endpoint, overrides `OTEL_EXPORTER_OTLP_ENDPOINT`| `http://localhost:4318/v1/traces` +`OTEL_TRACES_EXPORT_INTERVAL`| Span batch export interval in milliseconds (default: 5000)| `1000`, `10000` + +Spans redact user prompt text and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1` and `OTEL_LOG_TOOL_CONTENT=1` to include them. ### @@ -567,7 +586,7 @@ Backend considerations -Your choice of metrics and logs backends determines the types of analyses you can perform: +Your choice of metrics, logs, and traces backends determines the types of analyses you can perform: ### @@ -588,6 +607,17 @@ * **Log aggregation systems (for example, Elasticsearch, Loki)** : Full-text search, log analysis * **Columnar stores (for example, ClickHouse)** : Structured event analysis * **Full-featured observability platforms (for example, Honeycomb, Datadog)** : Correlation between metrics and events + +### + +​ + +For traces + +Choose a backend that supports distributed trace storage and span correlation: + + * **Distributed tracing systems (for example, Jaeger, Zipkin, Grafana Tempo)** : Span visualization, request waterfalls, latency analysis + * **Full-featured observability platforms (for example, Honeycomb, Datadog)** : Trace search and correlation with metrics and logs For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries. @@ -622,10 +652,11 @@ Security and privacy * Telemetry is opt-in and requires explicit configuration - * Raw file contents and code snippets are not included in metrics or events + * Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names, plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed + * Tool input and output content is not logged in trace spans by default. To include it, set `OTEL_LOG_TOOL_CONTENT=1`. When enabled, span events include full tool input and output content truncated at 60 KB per span. This can include raw file contents from Read tool results and Bash command output. Configure your telemetry backend to filter or redact these attributes as needed ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -12,8 +12,8 @@ export CLAUDE_CODE_ENABLE_TELEMETRY=1 # 2. Choose exporters (both are optional - configure only what you need) - export OTEL_METRICS_EXPORTER=otlp # Options: otlp, prometheus, console - export OTEL_LOGS_EXPORTER=otlp # Options: otlp, console + export OTEL_METRICS_EXPORTER=otlp # Options: otlp, prometheus, console, none + export OTEL_LOGS_EXPORTER=otlp # Options: otlp, console, none # 3. Configure OTLP endpoint (for OTLP exporter) export OTEL_EXPORTER_OTLP_PROTOCOL=grpc @@ -69,8 +69,8 @@ Environment Variable| Description| Example Values ---|---|--- `CLAUDE_CODE_ENABLE_TELEMETRY`| Enables telemetry collection (required)| `1` -`OTEL_METRICS_EXPORTER`| Metrics exporter types, comma-separated| `console`, `otlp`, `prometheus` -`OTEL_LOGS_EXPORTER`| Logs/events exporter types, comma-separated| `console`, `otlp` +`OTEL_METRICS_EXPORTER`| Metrics exporter types, comma-separated. Use `none` to disable| `console`, `otlp`, `prometheus`, `none` +`OTEL_LOGS_EXPORTER`| Logs/events exporter types, comma-separated. Use `none` to disable| `console`, `otlp`, `none` `OTEL_EXPORTER_OTLP_PROTOCOL`| Protocol for OTLP exporter, applies to all signals| `grpc`, `http/json`, `http/protobuf` `OTEL_EXPORTER_OTLP_ENDPOINT`| OTLP collector endpoint for all signals| `http://localhost:4317` `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL`| Protocol for metrics, overrides general setting| `grpc`, `http/json`, `http/protobuf` @@ -83,7 +83,7 @@ `OTEL_METRIC_EXPORT_INTERVAL`| Export interval in milliseconds (default: 60000)| `5000`, `60000` `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable -`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters (bash commands, MCP server/tool names, skill names) and tool input arguments in tool events (default: disabled)| `1` to enable +`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events: Bash commands, MCP server and tool names, skill names, and tool input (default: disabled)| `1` to enable `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes)| `900000` @@ -436,11 +436,11 @@ * `decision_source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` * `tool_result_size_bytes`: Size of the tool result in bytes * `mcp_server_scope`: MCP server scope identifier (for MCP tools) - * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters + * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters: * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds) * For MCP tools: includes `mcp_server_name`, `mcp_tool_name` * For Skill tool: includes `skill_name` - * `tool_input` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON-serialized tool arguments with long strings truncated. Bounded to ~4 K characters. Applies to all tools including MCP tools. + * `tool_input` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON-serialized tool arguments. Individual values over 512 characters are truncated, and the full payload is bounded to ~4 K characters. Applies to all tools including MCP tools. #### @@ -625,7 +625,7 @@ * Raw file contents and code snippets are not included in metrics or events * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` - * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, tool_result events include a `tool_parameters` attribute (bash commands, MCP server/tool names, skill names) and a `tool_input` attribute (file paths, URLs, search patterns, and other arguments). Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed + * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names, plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed ##
modified
Show diff (133 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -7,12 +7,6 @@ Quick start Configure OpenTelemetry using environment variables: - -Report incorrect code - -Copy - -Ask AI # 1. Enable telemetry export CLAUDE_CODE_ENABLE_TELEMETRY=1 @@ -46,12 +40,6 @@ Administrator configuration Administrators can configure OpenTelemetry settings for all users through the [managed settings file](</docs/en/settings#settings-files>). This allows for centralized control of telemetry settings across an organization. See the [settings precedence](</docs/en/settings#settings-precedence>) for more information about how settings are applied. Example managed settings configuration: - -Report incorrect code - -Copy - -Ask AI { "env": { @@ -95,7 +83,7 @@ `OTEL_METRIC_EXPORT_INTERVAL`| Export interval in milliseconds (default: 60000)| `5000`, `60000` `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable -`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool input arguments, MCP server/tool names, and skill names in tool events (default: disabled)| `1` to enable +`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters (bash commands, MCP server/tool names, skill names) and tool input arguments in tool events (default: disabled)| `1` to enable `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes)| `900000` @@ -131,12 +119,6 @@ Add to your `.claude/settings.json`: -Report incorrect code - -Copy - -Ask AI - { "otelHeadersHelper": "/bin/generate_opentelemetry_headers.sh" } @@ -149,12 +131,6 @@ The script must output valid JSON with string key-value pairs representing HTTP headers: -Report incorrect code - -Copy - -Ask AI - #!/bin/bash # Example: Multiple headers echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}" @@ -174,12 +150,6 @@ Multi-team organization support Organizations with multiple teams or departments can add custom attributes to distinguish between different groups using the `OTEL_RESOURCE_ATTRIBUTES` environment variable: - -Report incorrect code - -Copy - -Ask AI # Add custom attributes for team identification export OTEL_RESOURCE_ATTRIBUTES="department=engineering,team.id=platform,cost_center=eng-123" @@ -200,13 +170,7 @@ **Examples:** -Report incorrect code - -Copy - -Ask AI - - # ❌ Invalid - contains spaces + # ❌ Invalid - contains spaces export OTEL_RESOURCE_ATTRIBUTES="org.name=John's Organization" # ✅ Valid - use underscores or camelCase instead @@ -225,12 +189,6 @@ Example configurations Set these environment variables before running `claude`. Each block shows a complete configuration for a different exporter or deployment scenario: - -Report incorrect code - -Copy - -Ask AI # Console debugging (1-second intervals) export CLAUDE_CODE_ENABLE_TELEMETRY=1 @@ -478,11 +436,11 @@ * `decision_source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` * `tool_result_size_bytes`: Size of the tool result in bytes * `mcp_server_scope`: MCP server scope identifier (for MCP tools) - * `tool_parameters`: JSON string containing tool-specific parameters (when available) + * `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds) - * For MCP tools (when `OTEL_LOG_TOOL_DETAILS=1`): includes `mcp_server_name`, `mcp_tool_name` - * For Skill tool (when `OTEL_LOG_TOOL_DETAILS=1`): includes `skill_name` - * `tool_input` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON-serialized tool arguments. Individual values over 512 characters are truncated, and the full payload is bounded to ~4 K characters. Applies to all tools including MCP tools. + * For MCP tools: includes `mcp_server_name`, `mcp_tool_name` + * For Skill tool: includes `skill_name` + * `tool_input` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON-serialized tool arguments with long strings truncated. Bounded to ~4 K characters. Applies to all tools including MCP tools. #### @@ -664,10 +622,10 @@ Security and privacy * Telemetry is opt-in and requires explicit configuration - * Raw file contents and code snippets are not included in metrics or events. Tool execution events include bash commands and file paths in the `tool_parameters` field, which may contain sensitive values. If your commands may include secrets, configure your telemetry backend to filter or redact `tool_parameters` + * Raw file contents and code snippets are not included in metrics or events * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` - * Tool input arguments are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include MCP server/tool names and skill names plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact `tool_input` as needed + * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, tool_result events include a `tool_parameters` attribute (bash commands, MCP server/tool names, skill names) and a `tool_input` attribute (file paths, URLs, search patterns, and other arguments). Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed ##
modified
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -95,7 +95,7 @@ `OTEL_METRIC_EXPORT_INTERVAL`| Export interval in milliseconds (default: 60000)| `5000`, `60000` `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable -`OTEL_LOG_TOOL_DETAILS`| Enable logging of MCP server/tool names and skill names in tool events (default: disabled)| `1` to enable +`OTEL_LOG_TOOL_DETAILS`| Enable logging of tool input arguments, MCP server/tool names, and skill names in tool events (default: disabled)| `1` to enable `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes)| `900000` @@ -482,6 +482,7 @@ * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds) * For MCP tools (when `OTEL_LOG_TOOL_DETAILS=1`): includes `mcp_server_name`, `mcp_tool_name` * For Skill tool (when `OTEL_LOG_TOOL_DETAILS=1`): includes `skill_name` + * `tool_input` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON-serialized tool arguments. Individual values over 512 characters are truncated, and the full payload is bounded to ~4 K characters. Applies to all tools including MCP tools. #### @@ -666,7 +667,7 @@ * Raw file contents and code snippets are not included in metrics or events. Tool execution events include bash commands and file paths in the `tool_parameters` field, which may contain sensitive values. If your commands may include secrets, configure your telemetry backend to filter or redact `tool_parameters` * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` - * MCP server/tool names and skill names are not logged by default because they can reveal user-specific configurations. To include them, set `OTEL_LOG_TOOL_DETAILS=1` + * Tool input arguments are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include MCP server/tool names and skill names plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact `tool_input` as needed ##
added
Show diff (680 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -0,0 +1,677 @@ +Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, and events via the logs/events protocol. Configure your metrics and logs backends to match your monitoring requirements. + +## + +​ + +Quick start + +Configure OpenTelemetry using environment variables: + +Report incorrect code + +Copy + +Ask AI + + # 1. Enable telemetry + export CLAUDE_CODE_ENABLE_TELEMETRY=1 + + # 2. Choose exporters (both are optional - configure only what you need) + export OTEL_METRICS_EXPORTER=otlp # Options: otlp, prometheus, console + export OTEL_LOGS_EXPORTER=otlp # Options: otlp, console + + # 3. Configure OTLP endpoint (for OTLP exporter) + export OTEL_EXPORTER_OTLP_PROTOCOL=grpc + export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 + + # 4. Set authentication (if required) + export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-token" + + # 5. For debugging: reduce export intervals + export OTEL_METRIC_EXPORT_INTERVAL=10000 # 10 seconds (default: 60000ms) + export OTEL_LOGS_EXPORT_INTERVAL=5000 # 5 seconds (default: 5000ms) + + # 6. Run Claude Code + claude + +The default export intervals are 60 seconds for metrics and 5 seconds for logs. During setup, you may want to use shorter intervals for debugging purposes. Remember to reset these for production use. + +For full configuration options, see the [OpenTelemetry specification](<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options>). + +## + +​ + +Administrator configuration + +Administrators can configure OpenTelemetry settings for all users through the [managed settings file](</docs/en/settings#settings-files>). This allows for centralized control of telemetry settings across an organization. See the [settings precedence](</docs/en/settings#settings-precedence>) for more information about how settings are applied. Example managed settings configuration: + +Report incorrect code + +Copy + +Ask AI + + { + "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" + } + } + +Managed settings can be distributed via MDM (Mobile Device Management) or other device management solutions. Environment variables defined in the managed settings file have high precedence and cannot be overridden by users. + +## + +​ + +Configuration details + +### + +​ + +Common configuration variables + +Environment Variable| Description| Example Values +---|---|--- +`CLAUDE_CODE_ENABLE_TELEMETRY`| Enables telemetry collection (required)| `1` +`OTEL_METRICS_EXPORTER`| Metrics exporter types, comma-separated| `console`, `otlp`, `prometheus` +`OTEL_LOGS_EXPORTER`| Logs/events exporter types, comma-separated| `console`, `otlp` +`OTEL_EXPORTER_OTLP_PROTOCOL`| Protocol for OTLP exporter, applies to all signals| `grpc`, `http/json`, `http/protobuf` +`OTEL_EXPORTER_OTLP_ENDPOINT`| OTLP collector endpoint for all signals| `http://localhost:4317` +`OTEL_EXPORTER_OTLP_METRICS_PROTOCOL`| Protocol for metrics, overrides general setting| `grpc`, `http/json`, `http/protobuf` +`OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`| OTLP metrics endpoint, overrides general setting| `http://localhost:4318/v1/metrics` +`OTEL_EXPORTER_OTLP_LOGS_PROTOCOL`| Protocol for logs, overrides general setting| `grpc`, `http/json`, `http/protobuf` +`OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`| OTLP logs endpoint, overrides general setting| `http://localhost:4318/v1/logs` +`OTEL_EXPORTER_OTLP_HEADERS`| Authentication headers for OTLP| `Authorization=Bearer token` +`OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY`| Client key for mTLS authentication| Path to client key file +`OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE`| Client certificate for mTLS authentication| Path to client cert file +`OTEL_METRIC_EXPORT_INTERVAL`| Export interval in milliseconds (default: 60000)| `5000`, `60000` +`OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` +`OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable +`OTEL_LOG_TOOL_DETAILS`| Enable logging of MCP server/tool names and skill names in tool events (default: disabled)| `1` to enable +`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`| Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality| `delta`, `cumulative` +`CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes)| `900000` + +### + +​ + +Metrics cardinality control + +The following environment variables control which attributes are included in metrics to manage cardinality: + +Environment Variable| Description| Default Value| Example to Disable +---|---|---|--- +`OTEL_METRICS_INCLUDE_SESSION_ID`| Include session.id attribute in metrics| `true`| `false` +`OTEL_METRICS_INCLUDE_VERSION`| Include app.version attribute in metrics| `false`| `true` +`OTEL_METRICS_INCLUDE_ACCOUNT_UUID`| Include user.account_uuid and user.account_id attributes in metrics| `true`| `false` + +These variables help control the cardinality of metrics, which affects storage requirements and query performance in your metrics backend. Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. + +### + +​ + +Dynamic headers + +For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically: + +#### + +​ + +Settings configuration + +Add to your `.claude/settings.json`: + +Report incorrect code + +Copy + +Ask AI + + { + "otelHeadersHelper": "/bin/generate_opentelemetry_headers.sh" + } + +#### + +​ + +Script requirements + +The script must output valid JSON with string key-value pairs representing HTTP headers: + +Report incorrect code + +Copy + +Ask AI + + #!/bin/bash + # Example: Multiple headers + echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}" + +#### + +​ + +Refresh behavior + +The headers helper script runs at startup and periodically thereafter to support token refresh. By default, the script runs every 29 minutes. Customize the interval with the `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` environment variable. + +### + +​ + +Multi-team organization support + +Organizations with multiple teams or departments can add custom attributes to distinguish between different groups using the `OTEL_RESOURCE_ATTRIBUTES` environment variable: + +Report incorrect code + +Copy + +Ask AI + + # Add custom attributes for team identification + export OTEL_RESOURCE_ATTRIBUTES="department=engineering,team.id=platform,cost_center=eng-123" + +These custom attributes will be included in all metrics and events, allowing you to: + + * Filter metrics by team or department + * Track costs per cost center + * Create team-specific dashboards + * Set up alerts for specific teams + +**Important formatting requirements for OTEL_RESOURCE_ATTRIBUTES:** The `OTEL_RESOURCE_ATTRIBUTES` environment variable uses comma-separated key=value pairs with strict formatting requirements: + + * **No spaces allowed** : Values cannot contain spaces. For example, `user.organizationName=My Company` is invalid + * **Format** : Must be comma-separated key=value pairs: `key1=value1,key2=value2` + * **Allowed characters** : Only US-ASCII characters excluding control characters, whitespace, double quotes, commas, semicolons, and backslashes + * **Special characters** : Characters outside the allowed range must be percent-encoded + +**Examples:** + +Report incorrect code + +Copy + +Ask AI + + # ❌ Invalid - contains spaces + export OTEL_RESOURCE_ATTRIBUTES="org.name=John's Organization" + + # ✅ Valid - use underscores or camelCase instead + export OTEL_RESOURCE_ATTRIBUTES="org.name=Johns_Organization" + export OTEL_RESOURCE_ATTRIBUTES="org.name=JohnsOrganization" + + # ✅ Valid - percent-encode special characters if needed + export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization" + +Note: wrapping values in quotes doesn’t escape spaces. For example, `org.name="My Company"` results in the literal value `"My Company"` (with quotes included), not `My Company`. + +### + +​ + +Example configurations + +Set these environment variables before running `claude`. Each block shows a complete configuration for a different exporter or deployment scenario: + +Report incorrect code + +Copy + +Ask AI + + # Console debugging (1-second intervals) + export CLAUDE_CODE_ENABLE_TELEMETRY=1 + export OTEL_METRICS_EXPORTER=console + export OTEL_METRIC_EXPORT_INTERVAL=1000 + + # OTLP/gRPC + export CLAUDE_CODE_ENABLE_TELEMETRY=1 + export OTEL_METRICS_EXPORTER=otlp + export OTEL_EXPORTER_OTLP_PROTOCOL=grpc + export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 + + # Prometheus + export CLAUDE_CODE_ENABLE_TELEMETRY=1 + export OTEL_METRICS_EXPORTER=prometheus + + # Multiple exporters + export CLAUDE_CODE_ENABLE_TELEMETRY=1 + export OTEL_METRICS_EXPORTER=console,otlp + export OTEL_EXPORTER_OTLP_PROTOCOL=http/json + + # Different endpoints/backends for metrics and logs + export CLAUDE_CODE_ENABLE_TELEMETRY=1 + export OTEL_METRICS_EXPORTER=otlp + export OTEL_LOGS_EXPORTER=otlp + export OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=http/protobuf + export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://metrics.example.com:4318 + export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=grpc + export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://logs.example.com:4317 + + # Metrics only (no events/logs) + export CLAUDE_CODE_ENABLE_TELEMETRY=1 + export OTEL_METRICS_EXPORTER=otlp + export OTEL_EXPORTER_OTLP_PROTOCOL=grpc + export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 + + # Events/logs only (no metrics) + export CLAUDE_CODE_ENABLE_TELEMETRY=1 + export OTEL_LOGS_EXPORTER=otlp + export OTEL_EXPORTER_OTLP_PROTOCOL=grpc + export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 + +## + +​ + +Available metrics and events + +### + +​ + +Standard attributes + +All metrics and events share these standard attributes: + +Attribute| Description| Controlled By +---|---|--- +`session.id`| Unique session identifier| `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) +`app.version`| Current Claude Code version| `OTEL_METRICS_INCLUDE_VERSION` (default: false) +`organization.id`| Organization UUID (when authenticated)| Always included when available +`user.account_uuid`| Account UUID (when authenticated)| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) +`user.account_id`| Account ID in tagged format matching Anthropic admin APIs (when authenticated), such as `user_01BWBeN28...`| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) +`user.id`| Anonymous device/installation identifier, generated per Claude Code installation| Always included +`user.email`| User email address (when authenticated via OAuth)| Always included when available +`terminal.type`| Terminal type, such as `iTerm.app`, `vscode`, `cursor`, or `tmux`| Always included when detected + +Events additionally include the following attributes. These are never attached to metrics because they would cause unbounded cardinality: + + * `prompt.id`: UUID correlating a user prompt with all subsequent events until the next prompt. See Event correlation attributes. + * `workspace.host_paths`: host workspace directories selected in the desktop app, as a string array + +### + +​ + +Metrics + +Claude Code exports the following metrics: + +Metric Name| Description| Unit +---|---|--- +`claude_code.session.count`| Count of CLI sessions started| count +`claude_code.lines_of_code.count`| Count of lines of code modified| count +`claude_code.pull_request.count`| Number of pull requests created| count +`claude_code.commit.count`| Number of git commits created| count +`claude_code.cost.usage`| Cost of the Claude Code session| USD +`claude_code.token.usage`| Number of tokens used| tokens +`claude_code.code_edit_tool.decision`| Count of code editing tool permission decisions| count +`claude_code.active_time.total`| Total active time in seconds| s + +### + +​ + +Metric details + +Each metric includes the standard attributes listed above. Metrics with additional context-specific attributes are noted below. + +#### + +​ + +Session counter + +Incremented at the start of each session. **Attributes** : + + * All standard attributes + +#### + +​ + +Lines of code counter + +Incremented when code is added or removed. **Attributes** : + + * All standard attributes + * `type`: (`"added"`, `"removed"`) + +#### + +​ + +Pull request counter + +Incremented when creating pull requests via Claude Code. **Attributes** : + + * All standard attributes + +#### + +​ + +Commit counter + +Incremented when creating git commits via Claude Code. **Attributes** : + + * All standard attributes + +#### + +​ + +Cost counter + +Incremented after each API request. **Attributes** : + + * All standard attributes + * `model`: Model identifier (for example, “claude-sonnet-4-6”) + +#### + +​ + +Token counter + +Incremented after each API request. **Attributes** : + + * All standard attributes + * `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`) + * `model`: Model identifier (for example, “claude-sonnet-4-6”) + +#### + +​ + +Code edit tool decision counter + +Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage. **Attributes** : + + * All standard attributes + * `tool_name`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`) + * `decision`: User decision (`"accept"`, `"reject"`) + * `source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` + * `language`: Programming language of the edited file, such as `"TypeScript"`, `"Python"`, `"JavaScript"`, or `"Markdown"`. Returns `"unknown"` for unrecognized file extensions. + +#### + +​ + +Active time counter + +Tracks actual time spent actively using Claude Code, excluding idle time. This metric is incremented during user interactions (typing, reading responses) and during CLI processing (tool execution, AI response generation). **Attributes** : + + * All standard attributes + * `type`: `"user"` for keyboard interactions, `"cli"` for tool execution and AI responses + +### + +​ + +Events + +Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured): + +#### + +​ + +Event correlation attributes + +When a user submits a prompt, Claude Code may make multiple API calls and run several tools. The `prompt.id` attribute lets you tie all of those events back to the single prompt that triggered them. + +Attribute| Description +---|--- +`prompt.id`| UUID v4 identifier linking all events produced while processing a single user prompt + +To trace all activity triggered by a single prompt, filter your events by a specific `prompt.id` value. This returns the user_prompt event, any api_request events, and any tool_result events that occurred while processing that prompt. + +`prompt.id` is intentionally excluded from metrics because each prompt generates a unique ID, which would create an ever-growing number of time series. Use it for event-level analysis and audit trails only. + +#### + +​ + +User prompt event + +Logged when a user submits a prompt. **Event Name** : `claude_code.user_prompt` **Attributes** : + + * All standard attributes + * `event.name`: `"user_prompt"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `prompt_length`: Length of the prompt + * `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`) + +#### + +​ + +Tool result event + +Logged when a tool completes execution. **Event Name** : `claude_code.tool_result` **Attributes** : + + * All standard attributes + * `event.name`: `"tool_result"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `tool_name`: Name of the tool + * `success`: `"true"` or `"false"` + * `duration_ms`: Execution time in milliseconds + * `error`: Error message (if failed) + * `decision_type`: Either `"accept"` or `"reject"` + * `decision_source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` + * `tool_result_size_bytes`: Size of the tool result in bytes + * `mcp_server_scope`: MCP server scope identifier (for MCP tools) + * `tool_parameters`: JSON string containing tool-specific parameters (when available) + * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds) + * For MCP tools (when `OTEL_LOG_TOOL_DETAILS=1`): includes `mcp_server_name`, `mcp_tool_name` + * For Skill tool (when `OTEL_LOG_TOOL_DETAILS=1`): includes `skill_name` + +#### + +​ + +API request event + +Logged for each API request to Claude. **Event Name** : `claude_code.api_request` **Attributes** : + + * All standard attributes + * `event.name`: `"api_request"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `model`: Model used (for example, “claude-sonnet-4-6”) + * `cost_usd`: Estimated cost in USD + * `duration_ms`: Request duration in milliseconds + * `input_tokens`: Number of input tokens + * `output_tokens`: Number of output tokens + * `cache_read_tokens`: Number of tokens read from cache + * `cache_creation_tokens`: Number of tokens used for cache creation + * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active + +#### + +​ + +API error event + +Logged when an API request to Claude fails. **Event Name** : `claude_code.api_error` **Attributes** : + + * All standard attributes + * `event.name`: `"api_error"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `model`: Model used (for example, “claude-sonnet-4-6”) + * `error`: Error message + * `status_code`: HTTP status code as a string, or `"undefined"` for non-HTTP errors + * `duration_ms`: Request duration in milliseconds + * `attempt`: Attempt number (for retried requests) + * `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active + +#### + +​ + +Tool decision event + +Logged when a tool permission decision is made (accept/reject). **Event Name** : `claude_code.tool_decision` **Attributes** : + + * All standard attributes + * `event.name`: `"tool_decision"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `tool_name`: Name of the tool (for example, “Read”, “Edit”, “Write”, “NotebookEdit”) + * `decision`: Either `"accept"` or `"reject"` + * `source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` + +## + +​ + +Interpret metrics and events data + +The exported metrics and events support a range of analyses: + +### + +​ + +Usage monitoring + +Metric| Analysis Opportunity +---|--- +`claude_code.token.usage`| Break down by `type` (input/output), user, team, or model +`claude_code.session.count`| Track adoption and engagement over time +`claude_code.lines_of_code.count`| Measure productivity by tracking code additions/removals +`claude_code.commit.count` & `claude_code.pull_request.count`| Understand impact on development workflows + +### + +​ + +Cost monitoring + +The `claude_code.cost.usage` metric helps with: + + * Tracking usage trends across teams or individuals + * Identifying high-usage sessions for optimization + +Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex). + +### + +​ + +Alerting and segmentation + +Common alerts to consider: + + * Cost spikes + * Unusual token consumption + * High session volume from specific users + +All metrics can be segmented by `user.account_uuid`, `user.account_id`, `organization.id`, `session.id`, `model`, and `app.version`. + +### + +​ + +Event analysis + +The event data provides detailed insights into Claude Code interactions: **Tool Usage Patterns** : analyze tool result events to identify: + + * Most frequently used tools + * Tool success rates + * Average tool execution times + * Error patterns by tool type + +**Performance Monitoring** : track API request durations and tool execution times to identify performance bottlenecks. + +## + +​ + +Backend considerations + +Your choice of metrics and logs backends determines the types of analyses you can perform: + +### + +​ + +For metrics + + * **Time series databases (for example, Prometheus)** : Rate calculations, aggregated metrics + * **Columnar stores (for example, ClickHouse)** : Complex queries, unique user analysis + * **Full-featured observability platforms (for example, Honeycomb, Datadog)** : Advanced querying, visualization, alerting + +### + +​ + +For events/logs + + * **Log aggregation systems (for example, Elasticsearch, Loki)** : Full-text search, log analysis + * **Columnar stores (for example, ClickHouse)** : Structured event analysis + * **Full-featured observability platforms (for example, Honeycomb, Datadog)** : Correlation between metrics and events + +For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries. + +## + +​ + +Service information + +All metrics and events are exported with the following resource attributes: + + * `service.name`: `claude-code` + * `service.version`: Current Claude Code version + * `os.type`: Operating system type (for example, `linux`, `darwin`, `windows`) + * `os.version`: Operating system version string + * `host.arch`: Host architecture (for example, `amd64`, `arm64`) + * `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux) + * Meter Name: `com.anthropic.claude_code` + +## + +​ + +ROI measurement resources + +For a comprehensive guide on measuring return on investment for Claude Code, including telemetry setup, cost analysis, productivity metrics, and automated reporting, see the [Claude Code ROI Measurement Guide](<https://github.com/anthropics/claude-code-monitoring-guide>). This repository provides ready-to-use Docker Compose configurations, Prometheus and OpenTelemetry setups, and templates for generating productivity reports integrated with tools like Linear. + +## + +​ + +Security and privacy + + * Telemetry is opt-in and requires explicit configuration + * Raw file contents and code snippets are not included in metrics or events. Tool execution events include bash commands and file paths in the `tool_parameters` field, which may contain sensitive values. If your commands may include secrets, configure your telemetry backend to filter or redact `tool_parameters` + * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field + * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` + * MCP server/tool names and skill names are not logged by default because they can reveal user-specific configurations. To include them, set `OTEL_LOG_TOOL_DETAILS=1` + +## + +​ + +Monitor Claude Code on Amazon Bedrock + +For detailed Claude Code usage monitoring guidance for Amazon Bedrock, see [Claude Code Monitoring Implementation (Bedrock)](<https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md>).