Monitoring

Tags

official-docs claude-code-cli

Content

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.

Monitoring

Learn how to enable and configure OpenTelemetry for Claude Code.

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.

Quick start

Configure OpenTelemetry using environment variables:

```bash theme={null}

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, none export OTEL_LOGS_EXPORTER=otlp # Options: otlp, console, none

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


<Note>
  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.
</Note>

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](https://code.claude.com/en/settings#settings-files). This allows for centralized control of telemetry settings across an organization. See the [settings precedence](https://code.claude.com/en/settings#settings-precedence) for more information about how settings are applied.

Example managed settings configuration:

```json theme={null}
{
  "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. 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
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 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

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.

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, 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.

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:

```json theme={null} { "otelHeadersHelper": "/bin/generate_opentelemetry_headers.sh" }


#### Script requirements

The script must output valid JSON with string key-value pairs representing HTTP headers:

```bash theme={null}
#!/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:

```bash theme={null}

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

<Warning>
  **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:**

  ```bash theme={null}
  # ❌ 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`.
</Warning>

### Example configurations

Set these environment variables before running `claude`. Each block shows a complete configuration for a different exporter or deployment scenario:

```bash theme={null}
# 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:

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:

Lines of code counter

Incremented when code is added or removed.

Attributes:

Pull request counter

Incremented when creating pull requests via Claude Code.

Attributes:

Commit counter

Incremented when creating git commits via Claude Code.

Attributes:

Cost counter

Incremented after each API request.

Attributes:

Token counter

Incremented after each API request.

Attributes:

Code edit tool decision counter

Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage.

Attributes:

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:

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:

Tool result event

Logged when a tool completes execution.

Event Name: claude_code.tool_result

Attributes:

API request event

Logged for each API request to Claude.

Event Name: claude_code.api_request

Attributes:

API error event

Logged when an API request to Claude fails.

Event Name: claude_code.api_error

Attributes:

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:

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:

Tool decision event

Logged when a tool permission decision is made (accept/reject).

Event Name: claude_code.tool_decision

Attributes:

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:

Skill activated event

Logged when a skill is invoked.

Event Name: claude_code.skill_activated

Attributes:

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:

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:

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.

Event analysis

The event data provides detailed insights into Claude Code interactions:

Tool Usage Patterns: analyze tool result events to identify:

Performance Monitoring: track API request durations and tool execution times to identify performance bottlenecks.

Backend considerations

Your choice of metrics, logs, and traces backends determines the types of analyses you can perform:

For metrics

For events/logs

For traces

Choose a backend that supports distributed trace storage and span correlation:

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:

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. 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

Monitor Claude Code on Amazon Bedrock

For detailed Claude Code usage monitoring guidance for Amazon Bedrock, see Claude Code Monitoring Implementation (Bedrock).