Claude Code OpenTelemetry Metrics Setup: Complete Guide 2026

Nicola·
Claude Code OpenTelemetry Metrics Setup: Complete Guide 2026

How to Set Up OpenTelemetry Metrics for Claude Code in 2026

Look, installing the latest Claude Code CLI is the first step. Select a compatible OTLP backend before you enable telemetry. A solid base keeps data exports stable. We also get precise cost tracking for our workflows.

You need the most recent CLI version. Access built-in OpenTelemetry instrumentation requires it. Older releases might lack necessary exporters. They may miss semantic conventions for generative AI. The CLI records spans around model requests natively. It also tracks tool executions. Fresh installs capture these signals automatically. Custom patches become unnecessary. We recommend verifying your installation version. Check the latest release notes. Confirm OTLP support is active by default.

Supported observability backends

OpenTelemetry provides a vendor-neutral standard. We pick the backend that suits us. It aligns with our infrastructure. You can export metrics to Grafana Cloud. Datadog, Honeycomb, or AWS CloudWatch work too. The OpenTelemetry Collector offers a vendor-agnostic implementation of how to receive, process and export telemetry data. This component bridges the gap. Use it if your backend rejects direct OTLP streams. Switching providers becomes simple. Instrumentation code stays intact. Teams using AWS have an advantage. CloudWatch now supports OTLP ingestion. Bearer tokens handle authentication. Local setups become easier. They often sit outside the AWS ecosystem.

Network and authentication requirements

Secure connections matter. Usage data travels safely. Generate API keys from your provider. Bearer tokens are another option. These credentials validate CLI sessions. Unauthorized ingestion gets blocked. For example, bearer tokens allow tools running outside AWS (like Claude Code on developer laptops) to send metrics to CloudWatch without requiring the AWS SDK or IAM credential chains. Ensure your firewall permits outbound traffic. gRPC uses port 4317. HTTP relies on port 4318. Blocking these ports silences your metrics. You become blind to token consumption. Latency spikes stay hidden. Check local network policies. Make sure they ignore OTLP headers. Stripped headers break authentication.

Environment variables trigger OpenTelemetry export. Standard variables guide the CLI. They point to your backend. Define the endpoint URL first. Then add authentication headers. Restart the session to apply changes.

Setting environment variables

Standard variables drive the Claude Code CLI. They define telemetry destinations. Define the OTEL_EXPORTER_OTLP_ENDPOINT variable. Use the ingestion URL from your backend. This URL is the destination. It receives all metrics and traces. They generate during your coding sessions. Does your backend require authentication? Configure the OTEL_EXPORTER_OTLP_HEADERS variable. This header holds your API key. Or it holds a bearer token. Use a key-value format. For example, AWS CloudWatch supports OTLP ingestion. It uses bearer token authentication. This simplifies setup for local developers source. Tools outside AWS can send metrics. Complex IAM credential chains are unnecessary.

You must explicitly enable telemetry collection. Set CLAUDE_CODE_ENABLE_TELEMETRY to 1. This activates the export functionality source. The CLI ignores OTLP configuration without this flag. No observability data gets generated. Add these variables to your shell profile. Or use a project-specific .env file. They persist across terminal sessions this way. Restart the Claude Code session after updating. The CLI reads environment variables at startup. Changes during an active session do not take effect. Start a new session to apply them.

Choosing between gRPC and HTTP protocols

OpenTelemetry supports two primary transport protocols. gRPC and HTTP/protobuf are the options. Your choice depends on backend capabilities. Network constraints matter too. The gRPC protocol uses port 4317 by default. It offers higher performance. High-volume telemetry streams benefit from this. Backends like Honeycomb support it. Self-hosted OpenTelemetry Collectors do too. The HTTP protocol uses port 4318. It is more firewall-friendly. Cloud-based services often restrict non-standard ports. HTTP is easier to configure there.

You do not modify Claude Code source. The CLI detects the protocol automatically. It looks at the endpoint URL scheme. Explicit configuration variables work too. Connection timeouts occurring? Switch from gRPC to HTTP. This may resolve the issue. Flexibility ensures wide integration. You can monitor with Prometheus. Datadog or Grafana work as well. The OpenTelemetry framework is vendor-neutral source. You export data without changing code. This portability protects your investment. Your stack evolves over time. We suggest testing both protocols. Determine which offers reliable connectivity. Do this during initial setup.

Which metrics and traces does Claude Code emit by default?

Claude Code produces three signal types. It exports metrics as time series data. Events go through the logs protocol. Optional distributed traces use the traces protocol [https://code.claude.com/docs/en/monitoring-usage]. This approach separates cost tracking. Performance debugging remains distinct. You gain visibility into token consumption. Trace storage stays uncluttered. High-volume counters do not fill it. The system captures these signals automatically. Standard operations trigger this. No custom instrumentation is required. Basic observability works out of the box.

Understanding token usage metrics

Engineering leaders value cost attribution. Claude Code emits standard OpenTelemetry metrics. They track input and output token counts. This data helps budget forecasting. Correlate token volume with projects. Or link it to specific developers. The system emits claude_code.session.count. It triggers when a new session begins [https://code.claude.com/docs/en/monitoring-usage]. This counter measures agent adoption rates. It distinguishes active development from idle time.

The default export interval is 60 seconds [https://code.claude.com/docs/en/monitoring-usage]. This frequency balances data freshness. Network overhead remains low. You receive near-real-time insights. Spending trends become visible quickly. Metrics adhere to semantic conventions. Compatibility with various dashboards is ensured. Visualize data in Grafana easily. Datadog or AWS CloudWatch work too. Complex transformation pipelines are unnecessary. The standardized format reduces effort. It aids token optimization initiatives. Teams identify inefficient prompts quickly.

Tracing tool execution and latency

Traces offer a different perspective. They reveal internal agent mechanics. The CLI records spans around model requests. It tracks every tool execution too [https://code.claude.com/docs/en/agent-sdk/observability]. This granularity pinpoints bottlenecks. You might find a tool call adds latency. Model inference time may vary. Prompt complexity often drives this.

Trace data includes interaction durations. Detailed timing information is present. Events capture specific lifecycle moments. Session starts and errors are logged. This structured logging aids debugging. See which tool call triggered an exception. The Agent SDK passes configuration to the CLI. It handles all export logic [https://code.claude.com/docs/en/agent-sdk/observability]. Your application code stays clean. Separate telemetry clients are unnecessary. Traces provide necessary context. Effective context management relies on this. Refine agent instructions based on execution paths. This leads to reliable AI coding experiences. Your team benefits from faster workflows.

We confirm integration by generating test traffic. Cross-reference backend data with CLI outputs. This validation ensures accuracy. Your observability pipeline reflects reality. It tracks token optimization efforts correctly.

Testing the data pipeline

Start by executing a simple command. Use the Claude Code environment. A basic file read works. A short conversational prompt suffices. This generates sufficient telemetry. It triggers an export. Complex agent workflows are not needed. The system emits data on schedules. Metrics arrive every 60 seconds. Logs export every 5 seconds Source: https://code.claude.com/docs/en/monitoring-usage. Wait at least one minute. Allow the metrics buffer to flush.

Navigate to your observability platform. We support various backends. Grafana, Datadog, and AWS CloudWatch are options. Search for claude-code in your explorer. Or check the metrics dashboard. Using AWS CloudWatch? Ensure bearer token authentication is active. This method allows data transmission. Developer laptops send data easily. Complex IAM credential chains are avoided Source: https://aws.amazon.com/blogs/mt/analyzing-claude-code-usage-with-cloudwatch-and-opentelemetry/. New spans should appear. Look for markers like claude_code.session.count. This confirms session initialization. Dashboard empty? Check network firewall rules. Ports 4317 and 4318 must allow outbound traffic.

Validating metric accuracy

Raw presence is not enough. Verify numerical accuracy of transmitted data. Compare token counts in your backend. Check the summary in your local CLI. The CLI outputs total tokens. Input and output counts are shown. These must match trace attributes. Look for gen_ai.usage.input_tokens. Also check gen_ai.usage.output_tokens. Discrepancies often point to sampling rules. Misconfigured aggregators in the Collector cause this too.

Check the latency values as well. Trace duration should align with wall-clock time. Significant deviations suggest network latency. Clock synchronization issues are possible too. Accurate context management relies on precision. Data aligns? Your setup is complete. Trust the dashboard now. Use it for developer productivity analysis. Cost attribution becomes reliable.

Effective context management prevents spiraling costs. It preserves critical debugging data. We must balance granular telemetry. Efficient payload sizes maintain productivity. Implement targeted sampling. Use custom attributes. Capture high-value signals only. Avoid overwhelming backend storage. Unnecessary expense is avoided.

Sampling strategies for high-volume usage

High-frequency interactions generate volume. Blindly exporting every span is costly. Storage bills bloat quickly. Query performance slows down. Implement head-based sampling. Discard low-fidelity traces locally. Focus retention on errors. High latency sessions matter too. Significant token consumption warrants keeping data. Simple file reads do not. Successful noop operations rarely need persistence. Filtering these reduces noise. Anomalies impacting cost stand out.

The OpenTelemetry Collector offers a vendor-agnostic implementation. Process this data stream effectively. Define complex pipelines. Drop specific spans. Aggregate metrics before export. This keeps trace payloads small. Configure the collector to retain traces. Keep those exceeding a duration threshold. Or retain those with specific error codes. This strategy aligns with goals. Token optimization is the aim. Pay only for actionable insights.

Adding custom attributes for better filtering

Raw telemetry lacks business context. Custom attributes transform generic spans. They become searchable data points. Tag each session with project IDs. Add team names or feature flags. This enables precise filtering. Isolate traces for a microservice refactor. Or filter by client engagement.

Claude Code emits structured data. Enrich this data easily. The CLI has OpenTelemetry instrumentation built in. It records spans for requests. Extend these spans with attributes. Use git.commit.sha or user.role. Distinguish between development and staging. Production workloads separate easily. This supports better context management strategies. Correlate telemetry with code changes. Without custom tags, root cause analysis is tedious. Manual processes slow you down. Treat attributes as first-class citizens.

Connection failures usually stem from misconfigurations. Invalid authentication headers cause issues. Blocked network ports do too. Validate these settings systematically. Ensure telemetry reaches the backend.

Diagnosing authentication failures

Authentication errors occur frequently. The exporter cannot verify identity. A malformed API key is common. Or the key is missing entirely. Verify the OTEL_EXPORTER_OTLP_HEADERS variable. It must contain the correct pair. Using AWS CloudWatch? Rely on bearer token authentication. Send metrics from laptops easily. Complex IAM chains are avoided. Bearer tokens allow tools running outside AWS to send metrics to CloudWatch without requiring the AWS SDK. Check for extra spaces. Missing characters break the header string. A single typo prevents data acceptance.

Protocol mismatches are another issue. Backend expects HTTPS. Configuration points to HTTP. The connection fails immediately. Check your endpoint URL carefully. Match the protocol required by your vendor. Some providers enforce TLS/SSL strictly. SSL handshake errors in logs? Switch your endpoint. Use https:// instead of http://. This simple change resolves refusals.

Resolving network connectivity issues

Network barriers block telemetry data. Firewalls restrict outbound traffic. Corporate proxies do the same. Standard OTLP ports get blocked. Default ports are 4317 for gRPC. 4318 is for HTTP. Inspect local firewall rules. Ensure these ports are open. Operating within a restricted network? Route traffic through a proxy. Or use an OpenTelemetry Collector. The OpenTelemetry Collector offers a vendor-agnostic implementation of how to receive, process and export telemetry data. This local agent buffers data. It handles retry logic. Reliability improves significantly.

Enable debug logging in your SDK. Gain visibility into connection attempts. Detailed logs reveal failure points. Look for timeout errors. Connection refused messages are clues. They pinpoint network or config issues. Using the Agent SDK? Remember it runs the CLI as a child process. The Agent SDK runs the Claude Code CLI as a child process and communicates with it over a local pipe. Ensure the parent process has permissions. It must forward data successfully. Testing with a simple command helps. Isolate connectivity problems from logic errors.

Frequently Asked Questions

Does Claude Code support OpenTelemetry for cost tracking?
Yes. Claude Code natively emits OpenTelemetry metrics, traces, and logs for cost tracking. It records spans around model requests and tool executions, exporting token usage metrics as time-series data. You enable export by setting `CLAUDE_CODE_ENABLE_TELEMETRY=1` and configuring OTLP endpoint and authentication via environment variables (`OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_HEADERS`). No custom instrumentation is needed.
Can I send Claude Code metrics to Prometheus?
Yes, but not directly. Claude Code exports metrics via the OpenTelemetry Protocol (OTLP) using gRPC or HTTP. Prometheus does not natively ingest OTLP. The recommended approach is to deploy an OpenTelemetry Collector that receives OTLP data and scrapes it into Prometheus, or use the Collector’s Prometheus exporter. Alternatively, use a backend that supports both OTLP and Prometheus, such as Grafana Cloud.
How do I redact sensitive data from Claude Code traces?
Claude Code does not automatically redact sensitive data from traces. To redact, configure the OpenTelemetry Collector or your backend to apply processing rules (e.g., attribute masking, span filtering). For example, use the Collector’s `attributes` or `filter` processors to remove or obfuscate fields like API keys, file paths, or user input. You can also set `OTEL_EXPORTER_OTLP_HEADERS` to exclude sensitive headers from export. Review your OTLP exporter’s documentation for redaction features.
What is the overhead of enabling OpenTelemetry in Claude Code?
Overhead is minimal. Claude Code’s OpenTelemetry instrumentation is designed to be lightweight, emitting metrics and traces asynchronously with minimal impact on CLI responsiveness. The primary cost is network bandwidth and backend storage for exported data. If using gRPC, performance is slightly better than HTTP. To reduce overhead, adjust sampling rates or disable traces if only metrics are needed. In practice, developers report no noticeable slowdown during typical coding sessions.
Does Claude Code emit metrics for every tool call?
Yes. Claude Code automatically emits metrics for every tool call, including model requests and tool executions. These metrics capture token usage, latency, and success/failure counts. They are exported as time-series data via OTLP. You do not need to instrument each call manually. If you need to reduce volume, consider configuring sampling at the OpenTelemetry Collector level.
What environment variables are required to enable OpenTelemetry in Claude Code?
Three key variables: `CLAUDE_CODE_ENABLE_TELEMETRY=1` (enables export), `OTEL_EXPORTER_OTLP_ENDPOINT` (your backend’s ingestion URL), and `OTEL_EXPORTER_OTLP_HEADERS` (authentication, e.g., `Authorization=Bearer%20<token>`). Optionally set `OTEL_EXPORTER_OTLP_PROTOCOL` to `grpc` or `http/protobuf`. Restart the Claude Code session after setting them.
Can I use Claude Code with AWS CloudWatch for metrics?
Yes. AWS CloudWatch now supports OTLP ingestion. Set `OTEL_EXPORTER_OTLP_ENDPOINT` to your CloudWatch OTLP endpoint and use a bearer token in `OTEL_EXPORTER_OTLP_HEADERS` for authentication. This allows Claude Code running on local machines to send metrics without AWS SDK or IAM credentials.
Does Claude Code support gRPC or HTTP for telemetry export?
Both. Claude Code detects the protocol automatically based on the endpoint URL scheme. gRPC uses port 4317 (higher performance), HTTP uses port 4318 (firewall-friendly). You can override with `OTEL_EXPORTER_OTLP_PROTOCOL`. Choose based on your backend and network constraints.

Nicola

Developer and creator of vexp — a context engine for AI coding agents. I build tools that make AI coding assistants faster, cheaper, and actually useful on real codebases.

Keep reading

Related articles