Claude Code for Enterprise: Monitoring, ROI, and Cost Control Track
Module 2 of 8

OpenTelemetry Setup

Enable telemetry, configure OTLP exporters, connect to Prometheus or Grafana Cloud, and verify your first metrics are flowing in under 10 minutes.

12 min read

What You'll Learn

  • Enable OpenTelemetry in Claude Code with the correct environment variables
  • Choose between OTLP, Prometheus, and console exporters based on your stack
  • Connect Claude Code metrics to a Prometheus or Grafana Cloud backend
  • Verify that metrics and events are flowing correctly
  • Configure administrator-managed settings for team-wide deployment

What Claude Code Exports

Before configuring anything, understand what data Claude Code makes available through OpenTelemetry.

Metrics (time series data):

  • claude_code.session.count - How many CLI sessions started
  • claude_code.token.usage - Tokens used, broken down by type (input, output, cacheRead, cacheCreation) and model
  • claude_code.cost.usage - Estimated cost in USD per session, broken down by model
  • claude_code.lines_of_code.count - Lines added or removed
  • claude_code.commit.count - Git commits created
  • claude_code.pull_request.count - PRs created
  • claude_code.active_time.total - Active time in seconds (user interaction vs CLI processing)
  • claude_code.code_edit_tool.decision - Whether developers accept or reject code edits

Events (individual occurrences via logs protocol):

  • claude_code.user_prompt - Each prompt submitted (length only by default, content opt-in)
  • claude_code.api_request - Each API call (model, cost, duration, tokens)
  • claude_code.tool_result - Each tool execution (name, success/fail, duration)
  • claude_code.api_error - Failed API requests with retry counts
  • claude_code.tool_decision - Accept/reject decisions on tool permissions

Traces (beta, opt-in):

  • Distributed traces linking each user prompt to all API calls and tool executions it triggered
  • Full request waterfall visualization in your tracing backend

Every metric and event includes standard attributes: session.id, organization.id, user.account_uuid, user.account_id, user.email (OAuth only), and terminal.type.

Start With Metrics and Events

Traces are in beta and add complexity. Start with metrics (for dashboards) and events (for audit trails). Add traces later when you need to debug specific sessions or understand tool execution patterns.

Quick Start: Your First Metrics in 10 Minutes

The fastest way to verify everything works is the console exporter. It prints metrics to your terminal.

Step 1: Set the environment variables.

export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=console
export OTEL_LOGS_EXPORTER=console
export OTEL_METRIC_EXPORT_INTERVAL=10000

The first variable enables telemetry collection. The second and third tell Claude Code to print metrics and events to the console. The fourth reduces the export interval from 60 seconds to 10 seconds so you see results quickly.

Step 2: Run Claude Code.

Open a terminal and run claude. Send a prompt. Within 10 seconds, you will see metric data printed to the terminal including token counts, cost estimates, and session information.

Step 3: Verify the data.

Look for claude_code.token.usage and claude_code.cost.usage in the output. These confirm that telemetry is working. You should see attributes including model, type (input/output), and your session ID.

Once you confirm console output is working, switch to a real backend. The console exporter is for debugging only.

Try It Now

Set the four environment variables above, run Claude Code, and send one prompt. Watch for the metric output after 10 seconds. If you see token.usage and cost.usage data, your telemetry is working. You can proceed to connecting a real backend.

Connecting to Prometheus or Grafana Cloud

For production monitoring, you need a real metrics backend. The two most common options are self-hosted Prometheus or Grafana Cloud.

Option A: OTLP to Grafana Cloud (recommended for most teams)

Grafana Cloud has a free tier that handles small teams. Set these environment variables:

export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp-gateway-prod-us-central-0.grafana.net/otlp
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic YOUR_BASE64_ENCODED_CREDENTIALS"

Replace the endpoint with your Grafana Cloud OTLP endpoint (found in your Grafana Cloud portal under Connections > OpenTelemetry). The credentials are your Grafana Cloud instance ID and API token, base64-encoded.

Option B: Self-hosted Prometheus

If you run your own Prometheus, use the Prometheus exporter:

export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=prometheus

This exposes a Prometheus metrics endpoint that your Prometheus server can scrape. Configure your Prometheus scrape_configs to point to the exposed port.

Option C: OTLP to a local collector

Run an OpenTelemetry Collector locally or on your infrastructure:

export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317

The collector can then forward to any backend: Prometheus, Datadog, Honeycomb, ClickHouse, or others.

Separate Metrics and Logs Backends

You can send metrics and logs to different backends using separate endpoint variables. For example, metrics to Prometheus and events/logs to Elasticsearch:

OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://prometheus:4318

OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://elasticsearch:4317

This is useful when your organization already has established logging infrastructure.

Administrator Configuration for Teams

For teams with multiple developers, you do not want each person configuring their own telemetry. Use the managed settings file to push configuration to all Claude Code installations.

Create a managed settings JSON file:

{
  "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.yourcompany.com:4317",
    "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer your-team-token"
  }
}

Distribute this file via your MDM (Mobile Device Management) solution, configuration management tool, or internal deployment script. Environment variables defined in the managed settings file have high precedence and cannot be overridden by individual developers.

This ensures:

  • Every developer's Claude Code instance sends telemetry to the same backend
  • The configuration is consistent across the team
  • Developers cannot accidentally disable monitoring
  • Authentication credentials are managed centrally

Privacy considerations: By default, Claude Code does NOT log prompt content or tool arguments. Only prompt length is recorded. If you want to audit actual prompts (for compliance or security review), set OTEL_LOG_USER_PROMPTS=1. For tool details including bash commands and MCP tool names, set OTEL_LOG_TOOL_DETAILS=1. Discuss these settings with your security and legal teams before enabling them.

Multi-team tagging: Add OTEL_RESOURCE_ATTRIBUTES to tag metrics by department:

"OTEL_RESOURCE_ATTRIBUTES": "department=engineering,team.id=platform,cost_center=eng-123"

This allows per-team dashboards and cost allocation, which we cover in Module 8.

Do Not Log Prompts in Production Without Consent

OTEL_LOG_USER_PROMPTS=1 records the full text of every developer prompt. This may contain sensitive information: API keys, customer data, internal discussions. If you enable this, ensure developers are informed, your data retention policies cover it, and the telemetry backend has appropriate access controls.

Verifying Your Setup

After configuring your backend, verify that data is flowing correctly.

Check 1: Metrics are arriving.

In Grafana, go to Explore and select your Prometheus data source. Query claude_code_session_count (note: Prometheus converts dots to underscores). If you see data points, metrics are working.

Check 2: Events are arriving.

If using Loki or Elasticsearch, search for claude_code.user_prompt or claude_code.api_request. Each Claude Code session should generate at least one of each per prompt.

Check 3: Attributes are correct.

Verify that user.account_uuid, organization.id, and any custom OTEL_RESOURCE_ATTRIBUTES appear in the data. These are essential for per-developer and per-team analysis.

Check 4: Cost data is present.

Query claude_code_cost_usage. This should show non-zero values after any API request. The model attribute should distinguish between Opus, Sonnet, and Haiku usage.

Common issues:

  • Metrics not appearing: Check firewall rules between developer machines and the collector endpoint
  • Authentication errors: Verify the OTLP headers are correctly formatted (no spaces around the equals sign)
  • Missing attributes: Ensure developers are authenticated in Claude Code (OAuth or API key)
  • Delayed data: The default export interval is 60 seconds. Wait at least two intervals before troubleshooting

End-to-End Verification

Set up your chosen backend, configure the environment variables, run Claude Code, send three prompts of varying complexity (a simple question, a code edit, and a multi-file refactor). Then check your backend for all three types of data: metrics (counters), events (individual occurrences), and attributes (user/org identification). If all three are present, your monitoring stack is production-ready.

Core Insights

  • Claude Code exports 8 metrics, 5 event types, and optional distributed traces via OpenTelemetry, covering tokens, costs, sessions, code changes, and tool decisions
  • The console exporter is the fastest way to verify telemetry works (10 seconds), but switch to OTLP or Prometheus for production use
  • Administrator-managed settings files push telemetry configuration to all developers centrally, preventing gaps in monitoring coverage
  • Prompt content and tool arguments are NOT logged by default for privacy. Enable OTEL_LOG_USER_PROMPTS and OTEL_LOG_TOOL_DETAILS only with explicit consent and appropriate data handling policies
  • Use OTEL_RESOURCE_ATTRIBUTES to tag metrics by department, team, and cost center from day one. Adding tags later requires re-processing historical data