← ~/pillars / cost-engineering / instrumenting-claude-code

Instrumenting Claude Code

The complete cost-telemetry reference for Claude Code: OTel metrics and events, attribution attributes, cardinality and privacy controls, the status line, and a managed-settings rollout that survives opt-out.

updated 2026-07-07 ~5 min read pattern 01/07 Cost Engineering

on this page

Context. Layer one of the three-layer cost model is local telemetry: the harness knows the most, soonest. Claude Code ships the richest native cost instrumentation of any coding agent (per-request dollars, all four token types, and attribution down to the individual subagent), but all of it is off by default, and a fleet where three volunteers exported metrics once is not a measurement programme.

Forces. Telemetry that depends on per-developer opt-in decays to zero. The dollar figures are client-side estimates, so promising finance a reconciliation you cannot deliver burns trust. Metrics carry session.id by default, which is exactly what you want for debugging and exactly what explodes a time-series backend at fleet scale. And the events stream can carry prompts, responses, and tool inputs (powerful for audit, radioactive for privacy), so what you don’t export must be a decision, not an accident.

Resolution. Turn telemetry on for everyone via managed settings, which users cannot override; route it through a collector you control; keep the default redactions; choose your cardinality deliberately; and treat the dollars as steering data, never as a bill. The complete drop-in configuration is the OTel cost telemetry artifact.

The metrics: eight series, two that carry the money

With CLAUDE_CODE_ENABLE_TELEMETRY=1 and an OTEL_METRICS_EXPORTER set, Claude Code emits eight metric series (monitoring usage):

MetricWhat it countsUnit
claude_code.cost.usageEstimated cost of the sessionUSD
claude_code.token.usageTokens consumedtokens
claude_code.session.countSessions startedcount
claude_code.active_time.totalActive working times
claude_code.lines_of_code.countLines added or removedcount
claude_code.commit.countCommits createdcount
claude_code.pull_request.countPull requests createdcount
claude_code.code_edit_tool.decisionEdit permission decisionscount

The first two carry the money, and their attributes are where the analysis lives. claude_code.token.usage has a type attribute with four values (input, output, cacheRead, and cacheCreation), the same four usage types your invoice is built from, which is what makes cache economics measurable at all. Both series also carry model, query_source (main, subagent, or auxiliary), and, when detail logging is enabled, agent.name, skill.name, plugin.name, and mcp_server.name. That last group answers questions no invoice can: which skill is expensive, which MCP server’s tool calls dominate spend, and how much of the bill is subagents.

The other six series are the outcome side of cost per outcome: dollars over pull_request.count is a crude but honest first cut at cost-per-merged-PR, straight from one exporter.

The events: per-request dollars and a join key

Metrics aggregate; events itemise. With OTEL_LOGS_EXPORTER set, every API call emits a claude_code.api_request event carrying cost_usd, duration_ms, input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens, model, and request_id: a per-request cost ledger, client-side. Around it sit tool_result and tool_decision (what ran, what was blocked, and whether config, hook, or human decided), api_error, and compaction, whose pre_tokens and post_tokens put a number on what each compaction did to your context.

Every event carries two correlation keys: session.id, and prompt.id, a UUID linking everything that happened downstream of a single user prompt. prompt.id is the join that turns a pile of events into “that one prompt cost $1.90 across eleven API calls and forty tool invocations”, which is the granularity where optimisation decisions actually get made.

Attribution: put names on dollars

Metrics and events carry user.email and user.account_uuid when authenticated, plus organization.id: per-developer attribution with no work. For structure beyond that, OTEL_RESOURCE_ATTRIBUTES stamps custom dimensions on everything:

Terminal window
export OTEL_RESOURCE_ATTRIBUTES="department=engineering,team.id=platform,cost_center=eng-123"

Those keys become query dimensions (OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES defaults to true), so spend by team or cost centre is one sum by away.

Cardinality is a bill too

Telemetry has its own cost curve, and it is priced in label cardinality. Claude Code exposes the levers explicitly:

VariableIncludesDefault
OTEL_METRICS_INCLUDE_SESSION_IDsession.id on metricstrue
OTEL_METRICS_INCLUDE_ACCOUNT_UUIDuser.account_uuidtrue
OTEL_METRICS_INCLUDE_VERSIONapp.versionfalse
OTEL_METRICS_INCLUDE_ENTRYPOINTapp.entrypointfalse
OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTEScustom resource keystrue

Per-session series are invaluable while you are debugging spend and ruinous as a permanent fleet default: a thousand sessions a day is a thousand new series a day. A sane fleet posture: session IDs off on metrics, kept on events (where they are just fields, not series).

Privacy runs on the same pattern of explicit gates, all off by default: prompt text (OTEL_LOG_USER_PROMPTS), response text (OTEL_LOG_ASSISTANT_RESPONSES), and tool parameters and MCP names (OTEL_LOG_TOOL_DETAILS). Cost analysis needs none of them; leave them off until a security team asks in writing.

The status line: the telemetry a developer actually sees

Dashboards steer platform teams; developers steer by what is in front of them. The status line runs any script you configure and feeds it live session JSON: cost.total_cost_usd, context_window.used_percentage, lines added and removed, and, on Pro and Max plans, rate_limits.five_hour.used_percentage and rate_limits.seven_day.used_percentage, the closest thing to quota visibility any subscription vendor currently offers. The JSON’s session_id matches the OTel session.id, so the number a developer sees and the number on the platform dashboard reconcile by construction.

Worked example: a rollout that sticks

Fleet enforcement is a managed settings problem. A managed-settings.json in the OS-level location (/Library/Application Support/ClaudeCode/ on macOS, /etc/claude-code/ on Linux) sits at the top of the precedence order (above user, project, and even command-line settings), and its env block cannot be overridden. Distributed by MDM, it makes telemetry a property of the machine, not of developer diligence:

  1. Deploy the managed settings file pointing at your collector: the artifact carries the file, the collector configuration, and a starter dashboard.
  2. Verify locally before the fleet: OTEL_METRICS_EXPORTER=console with OTEL_METRIC_EXPORT_INTERVAL=1000 prints metrics to the terminal every second: proof of emission with no infrastructure.
  3. Watch four numbers in week one: daily spend by user, token mix by type, spend by model, and cacheRead share. The last one sets up the cache-economics work, because a low read share is usually money on fire.

What the numbers are not

The documentation is blunt and worth quoting: “Cost metrics are approximations. For official billing data, refer to your API provider” (monitoring usage). Layer one steers; layer three settles. Two more honest caveats. On subscription plans the dollar figures are API-equivalent value, not incremental spend: you prepaid; the telemetry tells you what the quota you burned was worth. And on Bedrock, this telemetry still works (it is emitted by the CLI, not the backend), but it remains a client-side estimate of spend that AWS accounts for elsewhere; billing-accurate per-developer attribution on Bedrock is its own pattern, next in this pillar.

// sources