●CODE 2.1.319 — Claude Code now moves MCP tasks to the background automatically, and a denyInsteadOfPrompting setting denies calls that would wait on a prompt●FABLE 5.2 — Claude Fable 5.2 and its fast mode are on the Claude API (11/9). Mythos 5.2 is limited to verified organizations●SONNET 4.5 — Retires on the Claude API on 11/30, 20 days left. Migrate to Sonnet 5.5●WINDOWS — Reports say hooks break silently only on Japanese-locale Windows; check the character encoding first●FAST — Opus 4.8 fast mode is deprecated and will be removed on 11/30. Migrate to Opus 5.5●NEW — I Put a Ten-Line Promise File at the To…●CODE 2.1.319 — Claude Code now moves MCP tasks to the background automatically, and a denyInsteadOfPrompting setting denies calls that would wait on a prompt●FABLE 5.2 — Claude Fable 5.2 and its fast mode are on the Claude API (11/9). Mythos 5.2 is limited to verified organizations●SONNET 4.5 — Retires on the Claude API on 11/30, 20 days left. Migrate to Sonnet 5.5●WINDOWS — Reports say hooks break silently only on Japanese-locale Windows; check the character encoding first●FAST — Opus 4.8 fast mode is deprecated and will be removed on 11/30. Migrate to Opus 5.5●NEW — I Put a Ten-Line Promise File at the To…
Observability for Claude Code with OpenTelemetry — A Production-Grade Tracing Guide for Agentic Workflows
Trace Claude Code agent runs end to end with OpenTelemetry. Hook integration, per-tool spans, MCP propagation, cost attribution, and sampling patterns that survive thousands of runs per day.
The first thing you discover when you start running Claude Code agents in production is that you're flying half-blind. /cost tells you what the session burned in total, but it won't tell you which tool call took 12 seconds, which MCP server retried four times, or where the loop started spinning. The session log scrolls past faster than you can read it.
I learned this the hard way. One morning my agent latency doubled overnight. The culprit turned out to be a single MCP server stuck on a network read, but it took me half a day to find that out by hand. With OpenTelemetry in place, I would have seen it the moment I opened the trace. Looking back, the half day I spent was not spent hunting for the cause — it was spent building a window to look through.
This guide walks through wiring Claude Code into OpenTelemetry so production runs become traceable, bottlenecks become obvious, and cost regressions become attributable to the specific tool call that caused them. We'll move from a minimal SDK setup to hook-based span emission, MCP context propagation, sampling that survives real traffic, and the dashboards worth keeping open every morning.
Why instrument Claude Code in the first place
Agent execution looks nothing like a normal request/response service. A single session can chain dozens of tool invocations, each fanning out to MCP servers and external APIs, with retry loops layered on top for self-correction. Trying to debug that with logs alone is the same pain you feel when you debug distributed systems with print statements.
In my experience, instrumentation buys you three concrete wins. First, bottlenecks become visible in seconds rather than hours. Second, cost regressions can be traced down to the project, the tool, and even the prompt shape that triggered them. Third, retry storms — those quiet, invisible loops that drain your monthly bill — start showing up the day they begin, not the week the invoice arrives.
Pick your signals before you pick your tools
OpenTelemetry has three signal types, and the temptation is to enable everything and figure it out later. Resist it. Decide upfront what each signal is for.
Traces capture one agent run as one trace, with parent/child spans modeling the call tree. This is the centerpiece for Claude Code observability
Metrics roll up time-series aggregates: invocation count, p50/p95 latency, error rate, token consumption. Use these for dashboards and alerts, not detective work
Logs capture per-event detail: the actual prompt, the actual stack trace. Necessary for drill-down, but you cannot afford to store every prompt forever — sampling and retention policies matter
The pragmatic split is traces in the middle, metrics around them for trend monitoring, and logs as the deep-dive layer when something breaks. The rest of this guide focuses on traces and treats metrics and logs as supporting cast.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦How to switch on Claude Code's own OpenTelemetry output (metrics, events, and beta traces), and where your own hook attributes should start
✦Hooks receive JSON on stdin, not environment variables: working Node.js and Python readers, and how to handle the failure event
✦A Tail-Based sampling plus metrics setup that keeps errors and slow traces, and a 5-step runbook for when traces don't show up
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Check the built-in telemetry before writing any hooks
An earlier version of this article assumed that hooks receive the tool name and token counts through environment variables. When I checked that against the official documentation, the assumption did not hold. On top of that, Claude Code can emit OpenTelemetry metrics, events, and (in beta) traces by itself. Opening that door first is the right order of work.
# Metrics and events (logs)export CLAUDE_CODE_ENABLE_TELEMETRY=1export OTEL_METRICS_EXPORTER=otlpexport OTEL_LOGS_EXPORTER=otlpexport OTEL_EXPORTER_OTLP_PROTOCOL=grpc # there is no default protocol, so always set itexport OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317# Traces (beta) need an extra flagexport CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1export OTEL_TRACES_EXPORTER=otlp
While you are still wiring things up, set OTEL_METRICS_EXPORTER=console before you stand up a collector, and read what comes out on stdout. On the backend side, seeing claude_code.session.count arrive means the pipe is connected.
The main metrics:
Metric
What it shows
Key attributes
claude_code.token.usage
Token consumption
type (input / output / cacheRead / cacheCreation), model, query_source
claude_code.cost.usage
Estimated cost per API request (USD)
model, query_source (main / subagent / auxiliary)
claude_code.session.count
Sessions started
start_type (fresh / resume / continue, among others)
claude_code.active_time.total
Active time in seconds
type (user / cli)
claude_code.code_edit_tool.decision
Edit tool accepts and rejects
tool_name, decision
Events arrive with a claude_code. prefix: tool_result, api_request, api_error, tool_decision, mcp_server_connection, and others. Retries and MCP connection failures show up there. Trace spans include claude_code.interaction (one root per prompt), claude_code.llm_request, claude_code.tool, and claude_code.tool.execution.
Prompt text, tool arguments, and response bodies are redacted by default. Unless you explicitly open them with flags such as OTEL_LOG_USER_PROMPTS=1 or OTEL_LOG_TOOL_DETAILS=1, they never reach your backend. Read the masking section later in this guide as advice for the moment you decide to undo that default yourself.
So where do your own hooks belong? My dividing line:
Take the numbers Claude Code already emits from Claude Code, and add by hand only the context that nobody else can attach.
A ticket number, the repository under change, whether a pre-deploy gate passed, traceparent propagation through your own MCP wrapper — Claude Code cannot know any of these. Read the rest of this guide as the implementation of that "add by hand" side.
Bootstrap OpenTelemetry with the smallest possible footprint
Start with the wrapper that launches Claude Code. Here's a minimal Node.js initializer.
// otel-init.mjs — load this first, before anything elseimport { NodeSDK } from "@opentelemetry/sdk-node";import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";import { Resource } from "@opentelemetry/resources";import { SemanticResourceAttributes } from "@opentelemetry/semantic-conventions";const sdk = new NodeSDK({ resource: new Resource({ [SemanticResourceAttributes.SERVICE_NAME]: "claude-code-agent", [SemanticResourceAttributes.SERVICE_VERSION]: process.env.AGENT_VERSION ?? "dev", "deployment.environment": process.env.NODE_ENV ?? "development", }), traceExporter: new OTLPTraceExporter({ url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces", headers: process.env.OTEL_AUTH_HEADER ? { Authorization: process.env.OTEL_AUTH_HEADER } : undefined, }),});try { sdk.start(); console.error("[otel] SDK started");} catch (err) { // Telemetry failures must never take production down — fail open. console.error("[otel] init failed, continuing without tracing:", err);}process.on("SIGTERM", async () => { try { await sdk.shutdown(); } catch (err) { console.error("[otel] shutdown error:", err); }});
The try/catch around sdk.start() is doing real work. The principle is fail open for telemetry: if Honeycomb is down or your collector is unreachable, the agent should keep running. Skip this and you've turned your observability vendor's maintenance window into a production outage of your own.
Run this with OTEL_EXPORTER_OTLP_ENDPOINT set to your collector and you should see [otel] SDK started on stderr. Without the env var, the agent should still run normally; only telemetry will be missing.
Emit a root span from the SessionStart hook
Now wire Claude Code's events into the SDK. The simplest pattern is to start a root span on SessionStart and end it on SessionEnd. If hook semantics are unfamiliar, the Claude Code Hooks complete practical guide covers all eight hook types in depth — read that first if needed.
The first thing to know is that hooks receive their input as JSON on stdin, not as environment variables. It carries session_id, tool_name, tool_input, tool_use_id, and more. Every hook below assumes this small reader:
// hooks/read-input.mjs — shared by every hook. Just reads the JSON from stdinexport async function readHookInput() { let raw = ""; for await (const chunk of process.stdin) raw += chunk; try { return JSON.parse(raw || "{}"); } catch { return {}; // never block the agent on a parse failure (fail-open) }}
When a tool fails, PostToolUseFailure fires instead of PostToolUse. You cannot read an exit status from the environment, so tell success from failure by the event name, and register the same script under both PostToolUse and PostToolUseFailure in settings.json.
One more honest caveat. Each hook runs as a short-lived process, so a span opened in SessionStart cannot be end()-ed inside that same process. The code below is an approximation: leave the start time in a state file, then rebuild the span in a later hook with an explicit startTime. If you need the exact parent/child structure of tool calls, the official traces (beta) from the previous section are more reliable.
// hooks/session-start.mjsimport { trace, context } from "@opentelemetry/api";import { writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import "./otel-init.mjs"; // initialize the SDK before anything elseimport { readHookInput } from "./read-input.mjs";const input = await readHookInput();const tracer = trace.getTracer("claude-code-session");const span = tracer.startSpan("claude_code.session", { attributes: { "session.id": input.session_id ?? "unknown", "session.cwd": process.cwd(), "session.user": process.env.USER ?? "unknown", },});// Persist the span context so subsequent hooks can attach as children.const spanCtx = span.spanContext();const handoff = { traceId: spanCtx.traceId, spanId: spanCtx.spanId, startedAt: Date.now(),};const stateFile = join(tmpdir(), `claude-otel-${input.session_id}.json`);writeFileSync(stateFile, JSON.stringify(handoff));console.error(`[otel] root span started: ${spanCtx.traceId}`);// Don't end the span here — SessionEnd will close it.
Claude Code hooks run as separate processes. You can't pass a traceparent header in memory the way you would inside a single HTTP service, so a small state file in /tmp/claude-otel-{sessionId}.json is the practical handoff mechanism for the trace ID and span ID.
The SessionEnd hook then reads this file back and closes the span. We'll cover the cross-process gotchas in the pitfalls section near the end.
Break down each tool call into a child span
The real value lands when you split each tool call into its own span using PreToolUse and PostToolUse.
// hooks/pre-tool-use.mjs — fired before a tool runsimport { trace, context } from "@opentelemetry/api";import { readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import "./otel-init.mjs";import { readHookInput } from "./read-input.mjs";const input = await readHookInput();const tracer = trace.getTracer("claude-code-tool");const stateFile = join(tmpdir(), `claude-otel-${input.session_id}.json`);const state = JSON.parse(readFileSync(stateFile, "utf8"));// Reconstruct the parent context from the persisted IDs.const parentCtx = trace.setSpanContext(context.active(), { traceId: state.traceId, spanId: state.spanId, traceFlags: 1, isRemote: true,});const toolName = input.tool_name ?? "unknown";const toolInput = JSON.stringify(input.tool_input ?? {});const span = tracer.startSpan( `tool.${toolName}`, { attributes: { "tool.name": toolName, "tool.input.length": toolInput.length, // Don't ship the full prompt — store length and a short preview only. "tool.input.preview": toolInput.slice(0, 200), }, }, parentCtx);const toolStateFile = join( tmpdir(), `claude-otel-tool-${input.tool_use_id}.json`);writeFileSync( toolStateFile, JSON.stringify({ traceId: span.spanContext().traceId, spanId: span.spanContext().spanId, startedAt: Date.now(), }));
The thing worth flagging here is the deliberate refusal to log full tool input as a span attribute. Prompts contain PII, code snippets, and sometimes credentials, and shipping all of that to a third-party observability vendor creates compliance headaches that are easier to avoid than to clean up. I cap the preview at 200 characters and store the length separately. If I genuinely need the full prompt for an investigation, I write it to a separate, access-controlled KV with a hash that I can correlate back to the trace.
Bridge the trace into your MCP servers
When Claude Code calls an MCP server, the MCP protocol (as of April 2026) doesn't standardize traceparent propagation. The practical workaround is to wrap your MCP client and inject W3C Trace Context yourself. The companion piece Claude Code MCP and the 500K context limit covers related MCP constraints worth being aware of.
If the MCP server runs OpenTelemetry too, it'll see the incoming traceparent and continue the same trace. Once that bridge is live, you can watch a single trace stretch from Claude Code → MCP server → downstream database in one view. Once it works, finding where a run stalls stops being guesswork and becomes something you can simply look at.
Take token, model, and cache numbers from the built-in metrics
For cost analysis, it is tempting to put token counts and model names on every tool span. But the input a hook receives contains neither tokens nor a model name. Environment variables like CLAUDE_INPUT_TOKENS in the earlier version of this code do not exist, so I removed them.
The built-in metrics cover this. claude_code.token.usage splits input, output, cacheRead, and cacheCreation through its type attribute, and also carries model and query_source (main conversation, subagent, auxiliary call). claude_code.cost.usage increments after each API request.
One principle from the earlier version is still worth keeping: put raw token counts first on the dashboard, and show money as a reference value. Price tables move with model updates and promotions, and the cost metric is an estimate. Reconcile against your actual bill in the billing console.
The first scaling pain you'll feel isn't latency — it's the storage bill. Suppose 5,000 runs per day times 50 spans per run — a back-of-the-envelope figure, not a measurement — is 250k spans per day. Ship all of that raw and the Honeycomb or Datadog invoice will surprise you in a bad way.
The combination that works in practice has three layers.
Probabilistic head sampling as a baseline: OTEL_TRACES_SAMPLER=traceidratio with OTEL_TRACES_SAMPLER_ARG=0.1 keeps 10% of traces. This is the floor for noisy projects
Always retain errors: A head sampler decides when the trace starts, so it cannot know about an error that happens later. Keeping every error needs Tail-Based Sampling at the collector
Force-keep important sessions: Tag specific traces (interactive dev sessions, CI release validations) and keep them unconditionally
Tail-Based sampling can't be done in the Node.js SDK alone, so the realistic deployment ends with an OpenTelemetry Collector hop in the middle.
Any trace that hits one of the three policies — error, latency over 5 seconds, or the random 10% — is forwarded. How much storage you save depends on your traffic and policies (estimate first, then confirm with real data), but the error and slow traces you care about survive.
Five signals worth a daily look
Once data starts accumulating, narrow the daily dashboard to these five tiles. Anything more and people stop reading it.
Session completion rate (success / failure / timeout): the headline number for agent health
P95 latency by tool: which tools tend to stall. Bash, WebFetch, and Edit deserve separate breakdowns
MCP error rate by server: catches a flaky MCP server before users do
Token consumption by model: shows where model switching or caching could save money. The built-in metrics supply it
Retry distribution: the share of tool calls retried 3+ times is a leading indicator of wasted spend
I recommend keeping these five tiles open in Grafana for five minutes each morning. If something looks off, let the dashboard link straight into the trace so the investigation starts one click away.
Add metrics for trend visibility, not detective work
Traces are excellent for debugging a single problematic run. They are terrible for answering "is the system healthy this week?" Metrics fill that gap. Wire a MeterProvider alongside the tracer so dashboards can render rolled-up time series without scanning every span.
// otel-metrics.mjs — call from otel-init.mjs after sdk.start()import { metrics } from "@opentelemetry/api";import { MeterProvider, PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";import { Resource } from "@opentelemetry/resources";const meterProvider = new MeterProvider({ resource: new Resource({ "service.name": "claude-code-agent" }), readers: [ new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter({ url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT?.replace("/v1/traces", "/v1/metrics"), }), exportIntervalMillis: 30_000, }), ],});metrics.setGlobalMeterProvider(meterProvider);const meter = metrics.getMeter("claude-code-agent");export const toolDurationHistogram = meter.createHistogram("claude.tool.duration", { unit: "ms", description: "Duration of a single Claude Code tool invocation",});export const sessionFailureCounter = meter.createCounter("claude.session.failures", { description: "Count of agent sessions that ended with a non-zero status",});
Update the PostToolUse hook to record into these metrics in addition to closing the span.
The advantage of metrics over span-scanning is cost. A histogram with 30-second resolution costs almost nothing to store and query for years, while the trace data behind it can be retained for only a few weeks. The split lets you ask "how has p95 latency drifted over the last quarter?" without paying for cold storage on millions of traces.
A Python alternative for projects that don't speak Node
Many Claude Code workflows are wrapped in Python — agent orchestrators, CI scripts, data pipelines. The OpenTelemetry concepts are identical; only the SDK shape changes.
# otel_init.py — import this at the top of any Python wrapperfrom opentelemetry import tracefrom opentelemetry.sdk.resources import Resourcefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessorfrom opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporterimport osresource = Resource.create({ "service.name": "claude-code-agent", "service.version": os.environ.get("AGENT_VERSION", "dev"), "deployment.environment": os.environ.get("ENV", "development"),})provider = TracerProvider(resource=resource)exporter = OTLPSpanExporter( endpoint=os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318/v1/traces"), headers={"authorization": os.environ["OTEL_AUTH_HEADER"]} if "OTEL_AUTH_HEADER" in os.environ else None,)provider.add_span_processor(BatchSpanProcessor(exporter))trace.set_tracer_provider(provider)tracer = trace.get_tracer("claude-code-agent")
The BatchSpanProcessor requires explicit shutdown to flush queued spans. In hook scripts that exit quickly, register a try/finally block:
# hooks/post_tool_use.pyimport os, sys, json, timefrom otel_init import tracer, providerfrom opentelemetry.trace import Status, StatusCodehook_input = json.load(sys.stdin)state_file = f"/tmp/claude-otel-tool-{hook_input['tool_use_id']}.json"with open(state_file) as f: state = json.load(f)duration_ms = int((time.time() * 1000) - state["startedAt"])exit_code = 1 if hook_input.get("hook_event_name") == "PostToolUseFailure" else 0with tracer.start_as_current_span(f"tool.end.{hook_input['tool_name']}") as span: span.set_attribute("tool.duration_ms", duration_ms) span.set_attribute("tool.exit_code", exit_code) if exit_code != 0: span.set_status(Status(StatusCode.ERROR, f"exit {exit_code}"))# Block until the span has been exported (bounded by 1.5s).try: provider.force_flush(timeout_millis=1500)finally: provider.shutdown()
The Python ergonomics are slightly nicer thanks to start_as_current_span as a context manager. If your team is split between languages, remember that the wire format is identical, so a single collector receives both equally.
Redact prompts properly when you do need them
There are cases where the 200-character preview isn't enough — debugging a strange retry loop usually requires the actual prompt. The wrong move is to drop the full prompt onto the span and ship it to your vendor. The right move is to redact at the source and write the redacted form to a separate, access-controlled store.
// redact.mjs — minimal redaction with a hook for project-specific rulesconst PATTERNS = [ // Common credential shapes { rx: /sk-[A-Za-z0-9]{16,}/g, mask: "[REDACTED:api_key]" }, { rx: /Bearer\s+[A-Za-z0-9._-]+/gi, mask: "[REDACTED:bearer]" }, // Email addresses { rx: /[\w.+-]+@[\w-]+\.[\w.-]+/g, mask: "[REDACTED:email]" }, // 16-digit numbers (rough credit card heuristic) { rx: /\d{16}/g, mask: "[REDACTED:card]" },];export function redact(input) { let out = input; for (const { rx, mask } of PATTERNS) { out = out.replace(rx, mask); } return out;}
Apply this before writing anything to a span attribute or to your prompt-archive store. Pair it with a strict allowlist of which projects are even permitted to archive prompts; default-deny is safer than default-allow for anything PII-adjacent.
What dashboards look like on the major backends
The five-signal dashboard from earlier translates to slightly different query shapes depending on where you ship traces.
In Honeycomb, each signal becomes a saved query: filter service.name = claude-code-agent, group by tool.name, plot P95(duration_ms) for the latency tile. Honeycomb's BubbleUp and trace inspection are particularly good for "why is this one trace 30 seconds long" investigations.
In Grafana Tempo + Prometheus, the metrics we emitted earlier feed Prometheus directly:
# Tool p95 latency over 5m, faceted by tool namehistogram_quantile(0.95, sum(rate(claude_tool_duration_bucket[5m])) by (tool_name, le))# Session failure rate over the last hour (if you define your own session-failure counter)sum(rate(claude_session_failures_total[1h])) / sum(rate(claude_session_total[1h]))# Token spend by model in the last 24h (built-in metric; the exact name depends on the translation rules, so check /metrics)sum by (model) (increase(claude_code_token_usage_tokens_total[24h]))
Tempo handles the trace storage and you click from a Prometheus alert into the corresponding trace via TraceQL.
In Datadog, you'll spend more time configuring tags than queries — Datadog's APM does most of the work once service, env, and tool.name are tagged consistently. The cost model is per-host plus per-span, so the Tail-Based Sampling rules from earlier are particularly important here.
The pragmatic choice is: pick whichever backend your team already pays for. The instrumentation we built is identical regardless.
Roll out in stages, not in one big bang
Lastly, a deployment cadence that tends to work for teams new to agent observability:
Week 1 is local Jaeger with a single dev agent. Start from the built-in output, and confirm that traces render and span attributes look right.
Week 2 is one production environment, with head sampling at 100% and no Tail-Based logic. Watch the volume.
Week 3 adds the Tail-Based collector and dials head sampling down to 10%. This is the week to validate that error traces still arrive.
Week 4 wires alerts and dashboards. Pull at least one historical incident from the trace store and check whether these alerts would have caught it.
Skipping straight to "everything on, everywhere" usually means quietly broken sampling that nobody notices until the storage bill arrives. A rollout that skips the verification week tends to stall later.
Pitfalls worth knowing in advance
Roughly in the order I tripped over them:
Hooks exit before exporters flush: Hook scripts are short-lived child processes. The default BatchSpanProcessor may exit before traces are sent. Either use SimpleSpanProcessor or call await sdk.shutdown() from a beforeExit handler
Trace ID file collisions: Persisting trace IDs to /tmp means parallel sessions can race. Always include the session_id in the filename
Attribute size limits: Don't try to stuff a full prompt into a single span attribute. The OTel spec safe ceiling is around 12KB per attribute, and exporters may reject larger ones
Don't proxy stdio MCP servers for trace injection: Trying to splice a tracing proxy in front of a stdio-based MCP server breaks JSON-RPC framing. Inject traceparent only for HTTP/SSE-based MCP servers
Telemetry latency leaking into your hot path: Synchronous exporters tie hook completion to your collector's response time. Use BatchSpanProcessor and bound the flush time with forceFlush({ timeout: 1500 }) before each hook exits
When traces don't show up: a debug runbook
The most demoralizing failure mode is wiring everything up and seeing nothing in the backend. The order I check, in roughly increasing painfulness:
Is the SDK actually starting? Check stderr for the [otel] SDK started line. If it's missing, the wrapper script isn't loading otel-init.mjs early enough — typically a side-effect of dynamic import ordering. Move the import to the top of the file
Is the endpoint reachable?curl -X POST $OTEL_EXPORTER_OTLP_ENDPOINT -d '{}' from the same machine. A 4xx is fine; it means the endpoint accepts traffic. Connection refused or DNS errors mean the agent will silently buffer spans and drop them
Are spans flushing before exit? Add console.error("[otel] forcing flush") and await sdk.shutdown() at the very end of each hook. If the line prints but no spans land, the issue is on the collector side
Is sampling dropping the traces you're looking at? During debug, set OTEL_TRACES_SAMPLER=always_on. If traces show up with always-on but not with the production sampler, your sampler config is wrong
Is the collector swallowing them? Check the collector's own logs. A misconfigured tail_sampling policy can drop everything silently. Run the collector with --config-source=file:./otel-collector.yaml and inspect startup output for warnings
If steps 1-5 pass and you still see nothing, swap to a local Jaeger via docker run jaegertracing/all-in-one and point the SDK there. Local Jaeger renders traces immediately, so you can isolate whether the problem is the SDK or your hosted backend.
Observability changes how you choose models
Once you start reading the numbers, the default model is the first thing worth revisiting. Before instrumenting, I tended to default to the most capable model "to be safe." I was deciding without data, so the real basis was mood.
The built-in claude_code.token.usage and claude_code.cost.usage metrics split by model and query_source. That means one query can tell you whether subagents or auxiliary calls are quietly running on a heavier model than you intended, not just the main conversation.
# Token consumption by model and by caller (the metric name depends on translation rules; check /metrics)sum by (model, query_source) ( increase(claude_code_token_usage_tokens_total[7d]))
What this shows is skew in consumption, not quality. Pair any decision to move to a lighter model with failure and rework rates on the same tasks. If you want per-tool latency by model, line up the tool.duration_ms you record in hooks against the claude_code.llm_request spans from the official traces (beta).
Make opening this table a weekly habit, and the invisible bleed of an agent that stayed pinned to a heavyweight model gets noticed early.
Closing thought
If you take one thing from this guide, let it be that observability for agentic systems is not optional infrastructure. Traditional services can survive on logs because the request/response shape is simple. Agents fan out, retry, and self-correct in ways that turn even simple tasks into multi-second multi-hop journeys. Without traces, you're guessing.
Start small — the built-in telemetry, a local Jaeger, then two hooks — and trust the process. Once that first trace renders end-to-end, the value becomes self-evident. From there, sampling, dashboards, and metrics layer on naturally as your agent footprint grows.
Pre-deploy checklist
Before rolling this out anywhere with real traffic:
Built-in OpenTelemetry output (metrics, events) is enabled first, and custom hooks are limited to adding your own context
SDK initialization is wrapped in try/catch; telemetry failure cannot take down the agent
Every hook (SessionStart / PreToolUse / PostToolUse / PostToolUseFailure / SessionEnd) reads the stdin JSON and emits and closes spans consistently
traceparent injection is restricted to HTTP/SSE MCP servers — never stdio
No span attribute carries full prompts or PII; preview is capped at 200 characters
Tail-Based sampling captures all errors, all slow traces, and a 10% probabilistic baseline
Daily span volume forecast fits inside your observability vendor's plan
Dashboard surfaces the five core signals; alerts fire on session failure rate > 5%, p95 latency > 30s, MCP error rate > 10%
Where to start if this feels like a lot
Don't try to ship everything at once. The pacing I'd suggest is one day on the built-in telemetry, one day on hook integration, and a few days on sampling tuning, in that order. For a weekend experiment, send the official metrics and traces (beta) into a local Jaeger container first.
The deeper sampling and Tail-Based logic can wait until you can see your real data volume. Don't over-engineer day one — the goal is "small and visible," not "perfect and theoretical."
Today, try CLAUDE_CODE_ENABLE_TELEMETRY=1 with OTEL_METRICS_EXPORTER=console and just watch what one session emits.
Share
Thank You for Reading
Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.