6 6
7All metrics are time series data exported via OpenTelemetry's standard metrics protocol, and events are exported via OpenTelemetry's logs/events protocol. It is the user's responsibility to ensure their metrics and logs backends are properly configured and that the aggregation granularity meets their monitoring requirements.7All metrics are time series data exported via OpenTelemetry's standard metrics protocol, and events are exported via OpenTelemetry's logs/events protocol. It is the user's responsibility to ensure their metrics and logs backends are properly configured and that the aggregation granularity meets their monitoring requirements.
8 8
9## Quick Start9## Quick start
10 10
11Configure OpenTelemetry using environment variables:11Configure OpenTelemetry using environment variables:
12 12
39 39
40For full configuration options, see the [OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options).40For full configuration options, see the [OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options).
41 41
42## Administrator Configuration42## Administrator configuration
43 43
44Administrators can configure OpenTelemetry settings for all users through the [managed settings file](/en/settings#settings-files). This allows for centralized control of telemetry settings across an organization. See the [settings precedence](/en/settings#settings-precedence) for more information about how settings are applied.44Administrators can configure OpenTelemetry settings for all users through the [managed settings file](/en/settings#settings-files). This allows for centralized control of telemetry settings across an organization. See the [settings precedence](/en/settings#settings-precedence) for more information about how settings are applied.
45 45
62 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.62 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.
63</Note>63</Note>
64 64
65## Configuration Details65## Configuration details
66 66
67### Common Configuration Variables67### Common configuration variables
68 68
69| Environment Variable | Description | Example Values |69| Environment Variable | Description | Example Values |
70| ----------------------------------------------- | --------------------------------------------------------- | ------------------------------------ |70| ----------------------------------------------- | --------------------------------------------------------- | ------------------------------------ |
84| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |84| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |
85| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |85| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |
86 86
87### Metrics Cardinality Control87### Metrics cardinality control
88 88
89The following environment variables control which attributes are included in metrics to manage cardinality:89The following environment variables control which attributes are included in metrics to manage cardinality:
90 90
96 96
97These 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.97These 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.
98 98
99### Dynamic Headers99### Dynamic headers
100 100
101For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically:101For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically:
102 102
103#### Settings Configuration103#### Settings configuration
104 104
105Add to your `.claude/settings.json`:105Add to your `.claude/settings.json`:
106 106
110}110}
111```111```
112 112
113#### Script Requirements113#### Script requirements
114 114
115The script must output valid JSON with string key-value pairs representing HTTP headers:115The script must output valid JSON with string key-value pairs representing HTTP headers:
116 116
120echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}"120echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}"
121```121```
122 122
123#### Important Limitations123#### Important limitations
124 124
125**Headers are fetched only at startup, not during runtime.** This is due to OpenTelemetry exporter architecture limitations.125**Headers are fetched only at startup, not during runtime.** This is due to OpenTelemetry exporter architecture limitations.
126 126
127For scenarios requiring frequent token refresh, use an OpenTelemetry Collector as a proxy that can refresh its own headers.127For scenarios requiring frequent token refresh, use an OpenTelemetry Collector as a proxy that can refresh its own headers.
128 128
129### Multi-Team Organization Support129### Multi-team organization support
130 130
131Organizations with multiple teams or departments can add custom attributes to distinguish between different groups using the `OTEL_RESOURCE_ATTRIBUTES` environment variable:131Organizations with multiple teams or departments can add custom attributes to distinguish between different groups using the `OTEL_RESOURCE_ATTRIBUTES` environment variable:
132 132
166 export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization"166 export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization"
167 ```167 ```
168 168
169 Note: Quoting the entire key=value pair (e.g., `"key=value with spaces"`) is not supported by the OpenTelemetry specification and will result in attributes being prefixed with quotes.169 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`.
170</Warning>170</Warning>
171 171
172### Example Configurations172### Example configurations
173 173
174```bash theme={null}174```bash theme={null}
175# Console debugging (1-second intervals)175# Console debugging (1-second intervals)
214export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317214export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
215```215```
216 216
217## Available Metrics and Events217## Available metrics and events
218 218
219### Standard Attributes219### Standard attributes
220 220
221All metrics and events share these standard attributes:221All metrics and events share these standard attributes:
222 222
223| Attribute | Description | Controlled By |223| Attribute | Description | Controlled By |
224| ------------------- | ------------------------------------------------------------- | --------------------------------------------------- |224| ------------------- | -------------------------------------------------------------------- | --------------------------------------------------- |
225| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |225| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |
226| `app.version` | Current Claude Code version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |226| `app.version` | Current Claude Code version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |
227| `organization.id` | Organization UUID (when authenticated) | Always included when available |227| `organization.id` | Organization UUID (when authenticated) | Always included when available |
228| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |228| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |
229| `terminal.type` | Terminal type (e.g., `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected |229| `terminal.type` | Terminal type (for example, `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected |
230 230
231### Metrics231### Metrics
232 232
243| `claude_code.code_edit_tool.decision` | Count of code editing tool permission decisions | count |243| `claude_code.code_edit_tool.decision` | Count of code editing tool permission decisions | count |
244| `claude_code.active_time.total` | Total active time in seconds | s |244| `claude_code.active_time.total` | Total active time in seconds | s |
245 245
246### Metric Details246### Metric details
247 247
248#### Session Counter248#### Session counter
249 249
250Incremented at the start of each session.250Incremented at the start of each session.
251 251
253 253
254* All [standard attributes](#standard-attributes)254* All [standard attributes](#standard-attributes)
255 255
256#### Lines of Code Counter256#### Lines of code counter
257 257
258Incremented when code is added or removed.258Incremented when code is added or removed.
259 259
262* All [standard attributes](#standard-attributes)262* All [standard attributes](#standard-attributes)
263* `type`: (`"added"`, `"removed"`)263* `type`: (`"added"`, `"removed"`)
264 264
265#### Pull Request Counter265#### Pull request counter
266 266
267Incremented when creating pull requests via Claude Code.267Incremented when creating pull requests via Claude Code.
268 268
270 270
271* All [standard attributes](#standard-attributes)271* All [standard attributes](#standard-attributes)
272 272
273#### Commit Counter273#### Commit counter
274 274
275Incremented when creating git commits via Claude Code.275Incremented when creating git commits via Claude Code.
276 276
278 278
279* All [standard attributes](#standard-attributes)279* All [standard attributes](#standard-attributes)
280 280
281#### Cost Counter281#### Cost counter
282 282
283Incremented after each API request.283Incremented after each API request.
284 284
285**Attributes**:285**Attributes**:
286 286
287* All [standard attributes](#standard-attributes)287* All [standard attributes](#standard-attributes)
288* `model`: Model identifier (e.g., "claude-sonnet-4-5-20250929")288* `model`: Model identifier (for example, "claude-sonnet-4-5-20250929")
289 289
290#### Token Counter290#### Token counter
291 291
292Incremented after each API request.292Incremented after each API request.
293 293
295 295
296* All [standard attributes](#standard-attributes)296* All [standard attributes](#standard-attributes)
297* `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)297* `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)
298* `model`: Model identifier (e.g., "claude-sonnet-4-5-20250929")298* `model`: Model identifier (for example, "claude-sonnet-4-5-20250929")
299 299
300#### Code Edit Tool Decision Counter300#### Code edit tool decision counter
301 301
302Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage.302Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage.
303 303
306* All [standard attributes](#standard-attributes)306* All [standard attributes](#standard-attributes)
307* `tool`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`)307* `tool`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`)
308* `decision`: User decision (`"accept"`, `"reject"`)308* `decision`: User decision (`"accept"`, `"reject"`)
309* `language`: Programming language of the edited file (e.g., `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions.309* `language`: Programming language of the edited file (for example, `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions.
310 310
311#### Active Time Counter311#### Active time counter
312 312
313Tracks actual time spent actively using Claude Code (not idle time). This metric is incremented during user interactions such as typing prompts or receiving responses.313Tracks actual time spent actively using Claude Code (not idle time). This metric is incremented during user interactions such as typing prompts or receiving responses.
314 314
320 320
321Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured):321Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured):
322 322
323#### User Prompt Event323#### User prompt event
324 324
325Logged when a user submits a prompt.325Logged when a user submits a prompt.
326 326
334* `prompt_length`: Length of the prompt334* `prompt_length`: Length of the prompt
335* `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)335* `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)
336 336
337#### Tool Result Event337#### Tool result event
338 338
339Logged when a tool completes execution.339Logged when a tool completes execution.
340 340
354* `tool_parameters`: JSON string containing tool-specific parameters (when available)354* `tool_parameters`: JSON string containing tool-specific parameters (when available)
355 * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `sandbox`355 * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `sandbox`
356 356
357#### API Request Event357#### API request event
358 358
359Logged for each API request to Claude.359Logged for each API request to Claude.
360 360
365* All [standard attributes](#standard-attributes)365* All [standard attributes](#standard-attributes)
366* `event.name`: `"api_request"`366* `event.name`: `"api_request"`
367* `event.timestamp`: ISO 8601 timestamp367* `event.timestamp`: ISO 8601 timestamp
368* `model`: Model used (e.g., "claude-sonnet-4-5-20250929")368* `model`: Model used (for example, "claude-sonnet-4-5-20250929")
369* `cost_usd`: Estimated cost in USD369* `cost_usd`: Estimated cost in USD
370* `duration_ms`: Request duration in milliseconds370* `duration_ms`: Request duration in milliseconds
371* `input_tokens`: Number of input tokens371* `input_tokens`: Number of input tokens
373* `cache_read_tokens`: Number of tokens read from cache373* `cache_read_tokens`: Number of tokens read from cache
374* `cache_creation_tokens`: Number of tokens used for cache creation374* `cache_creation_tokens`: Number of tokens used for cache creation
375 375
376#### API Error Event376#### API error event
377 377
378Logged when an API request to Claude fails.378Logged when an API request to Claude fails.
379 379
384* All [standard attributes](#standard-attributes)384* All [standard attributes](#standard-attributes)
385* `event.name`: `"api_error"`385* `event.name`: `"api_error"`
386* `event.timestamp`: ISO 8601 timestamp386* `event.timestamp`: ISO 8601 timestamp
387* `model`: Model used (e.g., "claude-sonnet-4-5-20250929")387* `model`: Model used (for example, "claude-sonnet-4-5-20250929")
388* `error`: Error message388* `error`: Error message
389* `status_code`: HTTP status code (if applicable)389* `status_code`: HTTP status code (if applicable)
390* `duration_ms`: Request duration in milliseconds390* `duration_ms`: Request duration in milliseconds
391* `attempt`: Attempt number (for retried requests)391* `attempt`: Attempt number (for retried requests)
392 392
393#### Tool Decision Event393#### Tool decision event
394 394
395Logged when a tool permission decision is made (accept/reject).395Logged when a tool permission decision is made (accept/reject).
396 396
401* All [standard attributes](#standard-attributes)401* All [standard attributes](#standard-attributes)
402* `event.name`: `"tool_decision"`402* `event.name`: `"tool_decision"`
403* `event.timestamp`: ISO 8601 timestamp403* `event.timestamp`: ISO 8601 timestamp
404* `tool_name`: Name of the tool (e.g., "Read", "Edit", "Write", "NotebookEdit", etc.)404* `tool_name`: Name of the tool (for example, "Read", "Edit", "Write", "NotebookEdit")
405* `decision`: Either `"accept"` or `"reject"`405* `decision`: Either `"accept"` or `"reject"`
406* `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`406* `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`
407 407
408## Interpreting Metrics and Events Data408## Interpreting metrics and events data
409 409
410The metrics exported by Claude Code provide valuable insights into usage patterns and productivity. Here are some common visualizations and analyses you can create:410The metrics exported by Claude Code provide valuable insights into usage patterns and productivity. Here are some common visualizations and analyses you can create:
411 411
412### Usage Monitoring412### Usage monitoring
413 413
414| Metric | Analysis Opportunity |414| Metric | Analysis Opportunity |
415| ------------------------------------------------------------- | --------------------------------------------------------- |415| ------------------------------------------------------------- | --------------------------------------------------------- |
418| `claude_code.lines_of_code.count` | Measure productivity by tracking code additions/removals |418| `claude_code.lines_of_code.count` | Measure productivity by tracking code additions/removals |
419| `claude_code.commit.count` & `claude_code.pull_request.count` | Understand impact on development workflows |419| `claude_code.commit.count` & `claude_code.pull_request.count` | Understand impact on development workflows |
420 420
421### Cost Monitoring421### Cost monitoring
422 422
423The `claude_code.cost.usage` metric helps with:423The `claude_code.cost.usage` metric helps with:
424 424
429 Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex).429 Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex).
430</Note>430</Note>
431 431
432### Alerting and Segmentation432### Alerting and segmentation
433 433
434Common alerts to consider:434Common alerts to consider:
435 435
439 439
440All metrics can be segmented by `user.account_uuid`, `organization.id`, `session.id`, `model`, and `app.version`.440All metrics can be segmented by `user.account_uuid`, `organization.id`, `session.id`, `model`, and `app.version`.
441 441
442### Event Analysis442### Event analysis
443 443
444The event data provides detailed insights into Claude Code interactions:444The event data provides detailed insights into Claude Code interactions:
445 445
446**Tool Usage Patterns**: Analyze tool result events to identify:446**Tool Usage Patterns**: analyze tool result events to identify:
447 447
448* Most frequently used tools448* Most frequently used tools
449* Tool success rates449* Tool success rates
450* Average tool execution times450* Average tool execution times
451* Error patterns by tool type451* Error patterns by tool type
452 452
453**Performance Monitoring**: Track API request durations and tool execution times to identify performance bottlenecks.453**Performance Monitoring**: track API request durations and tool execution times to identify performance bottlenecks.
454 454
455## Backend Considerations455## Backend considerations
456 456
457Your choice of metrics and logs backends will determine the types of analyses you can perform:457Your choice of metrics and logs backends determines the types of analyses you can perform:
458 458
459### For Metrics:459### For metrics
460 460
461* **Time series databases (e.g., Prometheus)**: Rate calculations, aggregated metrics461* **Time series databases (for example, Prometheus)**: Rate calculations, aggregated metrics
462* **Columnar stores (e.g., ClickHouse)**: Complex queries, unique user analysis462* **Columnar stores (for example, ClickHouse)**: Complex queries, unique user analysis
463* **Full-featured observability platforms (e.g., Honeycomb, Datadog)**: Advanced querying, visualization, alerting463* **Full-featured observability platforms (for example, Honeycomb, Datadog)**: Advanced querying, visualization, alerting
464 464
465### For Events/Logs:465### For events/logs
466 466
467* **Log aggregation systems (e.g., Elasticsearch, Loki)**: Full-text search, log analysis467* **Log aggregation systems (for example, Elasticsearch, Loki)**: Full-text search, log analysis
468* **Columnar stores (e.g., ClickHouse)**: Structured event analysis468* **Columnar stores (for example, ClickHouse)**: Structured event analysis
469* **Full-featured observability platforms (e.g., Honeycomb, Datadog)**: Correlation between metrics and events469* **Full-featured observability platforms (for example, Honeycomb, Datadog)**: Correlation between metrics and events
470 470
471For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries.471For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries.
472 472
473## Service Information473## Service information
474 474
475All metrics and events are exported with the following resource attributes:475All metrics and events are exported with the following resource attributes:
476 476
477* `service.name`: `claude-code`477* `service.name`: `claude-code`
478* `service.version`: Current Claude Code version478* `service.version`: Current Claude Code version
479* `os.type`: Operating system type (e.g., `linux`, `darwin`, `windows`)479* `os.type`: Operating system type (for example, `linux`, `darwin`, `windows`)
480* `os.version`: Operating system version string480* `os.version`: Operating system version string
481* `host.arch`: Host architecture (e.g., `amd64`, `arm64`)481* `host.arch`: Host architecture (for example, `amd64`, `arm64`)
482* `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux)482* `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux)
483* Meter Name: `com.anthropic.claude_code`483* Meter Name: `com.anthropic.claude_code`
484 484
485## ROI Measurement Resources485## ROI measurement resources
486 486
487For 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.487For 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.
488 488
489## Security/Privacy Considerations489## Security/privacy considerations
490 490
491* Telemetry is opt-in and requires explicit configuration491* Telemetry is opt-in and requires explicit configuration
492* Sensitive information like API keys or file contents are never included in metrics or events492* Sensitive information like API keys or file contents are never included in metrics or events