Claude Code OpenTelemetry Traces in Self-Hosted Langfuse
I wanted to see my Claude Code sessions in Langfuse: every turn, every model call, every tool call, with tokens and cost. Langfuse’s documented answer is a plugin that runs as a Stop hook. After each response it reads the session transcript and ships the turn. That works, but I wanted Claude Code’s own OpenTelemetry export to do the job.
It mostly works. Here’s the setup, what arrives, the OpenTelemetry Collector config that fills in most of the blanks, and a logs-to-traces bridge in the same collector that recovers the replies which for some reason are missing from the traces. At the end there’s a short comparison with the plugin, which I ended up running alongside it. The plugin itself gets its own post.
Run Langfuse locally
The Langfuse repo ships a docker-compose.yml with everything: web, worker, Postgres, ClickHouse, Redis, and MinIO. Headless initialization creates the org, project, API keys, and a login user on first boot, so there’s no clicking through a setup screen. Put this in a .env next to the compose file:
SALT=$(openssl rand -hex 16)
ENCRYPTION_KEY=$(openssl rand -hex 32)
NEXTAUTH_SECRET=$(openssl rand -hex 32)
LANGFUSE_INIT_ORG_ID=local-org
LANGFUSE_INIT_ORG_NAME=Local
LANGFUSE_INIT_PROJECT_ID=claude-code
LANGFUSE_INIT_PROJECT_NAME=Claude Code
LANGFUSE_INIT_PROJECT_PUBLIC_KEY=pk-lf-local
LANGFUSE_INIT_PROJECT_SECRET_KEY=sk-lf-local
LANGFUSE_INIT_USER_EMAIL=[email protected]
LANGFUSE_INIT_USER_NAME=you
LANGFUSE_INIT_USER_PASSWORD=<something random>
(Write the actual generated values into the file. The $(...) lines only expand if you create it with a shell heredoc.) Then docker compose up -d and log in at http://localhost:3000. The LANGFUSE_INIT_* values only apply to empty databases, so changing them later means docker compose down -v first.
Point Claude Code at it
Claude Code’s tracing is a beta behind its own flag. These go in the env block of ~/.claude/settings.json:
"CLAUDE_CODE_ENABLE_TELEMETRY": "1",
"CLAUDE_CODE_ENHANCED_TELEMETRY_BETA": "1",
"OTEL_TRACES_EXPORTER": "otlp",
"OTEL_EXPORTER_OTLP_TRACES_PROTOCOL": "http/protobuf",
"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT": "http://localhost:3000/api/public/otel/v1/traces",
"OTEL_EXPORTER_OTLP_TRACES_HEADERS": "Authorization=Basic <base64 of pk:sk>",
"OTEL_METRICS_EXPORTER": "none",
"OTEL_LOGS_EXPORTER": "none",
"OTEL_LOG_USER_PROMPTS": "1",
"OTEL_LOG_TOOL_DETAILS": "1",
"OTEL_LOG_TOOL_CONTENT": "1"
Metrics and logs are off on purpose. Langfuse’s metrics endpoint accepts OTLP and throws it away. It’s a no-op route that checks your key and returns 200, added so that OTel setups pointing OTEL_EXPORTER_OTLP_ENDPOINT at Langfuse don’t log a 404 for every metrics export. Langfuse computes its own tokens, cost, and latency from traces instead. Leaving Claude Code’s metrics on would look like it works and store nothing. There’s no logs endpoint at all. Traces are the only signal that lands. (Logs come back later in this post, sent to an OTel collector rather than to Langfuse.)
Settings are read at startup, so quitting and resuming the session is enough to pick them up.
What arrives
One trace per user turn, grouped by Claude Code’s session ID, so the Sessions view lines up with actual conversations:
claude_code.interaction (AGENT)
├─ claude_code.llm_request (GENERATION) model, tokens incl. cache, cost
├─ claude_code.tool.blocked_on_user (SPAN) time waiting on a permission prompt
└─ claude_code.tool.execution (TOOL)
└─ Bash / Edit / Read / ... (TOOL)
The structure, timing, model, token usage, and cost are all good out of the box. Langfuse maps the spans from their generic gen_ai.* attributes; it has no Claude Code-specific handling. A message you send mid-turn stays in that turn’s trace.
The catch: every Input and Output field was empty. The content was there, but as metadata. Your prompt arrives as user_prompt on the interaction span, the Bash command as full_command, and tool output as a span event named tool.output. Langfuse doesn’t know those names, and it ignores span events. Someone hit the same wall and asked Langfuse for native mapping in discussion #18422.
Rename attributes with a collector
Langfuse checks its own keys (langfuse.observation.input, langfuse.observation.output, langfuse.trace.input) before anything else. So the fix is an OpenTelemetry Collector between the two that copies Claude Code’s attributes into those keys. It’s all config, using the contrib image’s transform processor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
transform/claude_code:
error_mode: ignore
trace_statements:
- context: span
statements:
- set(span.attributes["langfuse.observation.input"], span.attributes["user_prompt"]) where span.name == "claude_code.interaction" and span.attributes["user_prompt"] != nil
- set(span.attributes["langfuse.trace.input"], span.attributes["user_prompt"]) where span.name == "claude_code.interaction" and span.attributes["user_prompt"] != nil
- set(span.attributes["langfuse.observation.input"], span.attributes["full_command"]) where span.attributes["langfuse.observation.input"] == nil and span.attributes["full_command"] != nil
- set(span.attributes["langfuse.observation.input"], span.attributes["file_path"]) where span.attributes["langfuse.observation.input"] == nil and span.attributes["file_path"] != nil
- context: spanevent
statements:
- set(span.attributes["langfuse.observation.output"], spanevent.attributes["output"]) where spanevent.name == "tool.output" and spanevent.attributes["output"] != nil
- set(span.attributes["langfuse.observation.output"], spanevent.attributes["diff"]) where spanevent.name == "tool.output" and span.attributes["langfuse.observation.output"] == nil and spanevent.attributes["diff"] != nil
batch: {}
exporters:
otlp_http/langfuse:
endpoint: http://langfuse-web:3000/api/public/otel
headers:
Authorization: "Basic ${env:LANGFUSE_AUTH}"
service:
pipelines:
traces:
receivers: [otlp]
processors: [transform/claude_code, batch]
exporters: [otlp_http/langfuse]
The two context: groups matter. My first version was one flat list of statements. The collector inferred spanevent context for all of them, which means the statements run once per span event. Spans with no events, like the interaction span carrying the prompt, were silently skipped. Tool spans worked and the prompt didn’t, which is a confusing result until you know why.
The collector runs on Langfuse’s Docker network so it can reach langfuse-web directly:
services:
otel-collector:
image: otel/opentelemetry-collector-contrib:0.165.0
restart: always
command: ["--config=/etc/otelcol/collector.yaml"]
volumes:
- ./collector.yaml:/etc/otelcol/collector.yaml:ro
environment:
LANGFUSE_AUTH: ${LANGFUSE_AUTH}
ports:
- 127.0.0.1:4318:4318
networks: [langfuse]
networks:
langfuse:
name: langfuse_default
external: true
LANGFUSE_AUTH (the base64 of pk:sk) lives in that folder’s .env. Then Claude Code points at the collector, and the header line comes out of settings because the collector adds it:
"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT": "http://localhost:4318/v1/traces"
otelcol-contrib validate --config=... catches syntax errors before you restart anything. It did not catch the context problem above; only sending a real span did.
What you get, and the gap
After one more resume, the turn shows my prompt as its input, Bash spans show the command and its stdout, and Edit spans show the file path and the diff. That’s live, as the session runs.
What’s still missing is the model’s own text, meaning Claude’s replies on the generation spans. Claude Code has an attribute for it (response.model_output), but it’s only set in a “detailed” tracing mode. That mode needs ENABLE_BETA_TRACING_DETAILED and a BETA_TRACING_ENDPOINT, and on top of those a check that looks like a server-side flag. I set both variables, resumed, and nothing changed, so it isn’t on for my account. OTEL_LOG_ASSISTANT_RESPONSES doesn’t add it to spans either; it emits a log event instead (more on that below). Claude Code also redacts extended thinking from all of its telemetry.
If the detailed mode ever opens up, the collector needs one more line, mapping response.model_output to the generation’s output. In practice it isn’t there: none of the roughly 1,800 claude_code.llm_request spans from five days of local use carried it.
Getting the replies from logs
Claude Code does export the replies, just not as spans. OTEL_LOG_RAW_API_BODIES=1 emits the raw API request and response for every model call as OTel log events, api_request_body and api_response_body. Langfuse has nowhere to put logs, but the collector does. I sent logs to it alongside traces:
"OTEL_LOGS_EXPORTER": "otlp",
"OTEL_EXPORTER_OTLP_LOGS_PROTOCOL": "http/protobuf",
"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT": "http://localhost:4318/v1/logs",
"OTEL_LOG_RAW_API_BODIES": "1"
Before building anything I pointed a logs pipeline at the debug exporter and looked at one record. An api_response_body record has:
body: the full Messages API response as a JSON string, with text blocks,tool_useblocks and their inputs,stop_reason, and usagerequest_id,model,message.id,session.id- a trace ID that matches the turn’s trace in Langfuse, and a span ID that is the turn’s
claude_code.interactionspan
That trace context is what makes this possible. The span ID isn’t the specific llm_request span, though. Only request_id ties a response to its exact call, and the collector can’t join two streams on a key. So each reply becomes a new span under the turn, as a sibling of the request that produced it, rather than filling in that generation’s Output. That was fine with me.
OTTL can’t move data from logs to traces; a transform only rewrites the signal it’s in. Moving between signals takes a connector. The contrib image has otlp_json, which reads OTLP JSON out of a log body and emits it as real telemetry. So the transform rewrites each response log’s body into the OTLP JSON for one span, and the connector turns that into a trace:
processors:
filter/api_response_body:
error_mode: ignore
logs:
log_record:
- 'log.attributes["event.name"] != "api_response_body"'
- 'log.trace_id.string == ""'
transform/response_to_span:
error_mode: ignore
log_statements:
- context: log
statements:
- 'set(log.body, String({"resourceSpans": [{"resource": {"attributes": [{"key": "service.name", "value": {"stringValue": "claude-code"}}]}, "scopeSpans": [{"scope": {"name": "claude-code-response-bridge"}, "spans": [{"traceId": log.trace_id.string, "spanId": Substring(SHA256(log.attributes["request_id"]), 0, 16), "parentSpanId": log.span_id.string, "name": "claude_code.llm_response", "kind": 1, "startTimeUnixNano": log.time_unix_nano, "endTimeUnixNano": log.time_unix_nano, "attributes": [{"key": "langfuse.observation.output", "value": {"stringValue": log.attributes["body"]}}, {"key": "request_id", "value": {"stringValue": log.attributes["request_id"]}}, {"key": "model", "value": {"stringValue": log.attributes["model"]}}, {"key": "session.id", "value": {"stringValue": log.attributes["session.id"]}}]}]}]}]}))'
connectors:
otlp_json: {}
service:
pipelines:
logs/api_response_body:
receivers: [otlp]
processors: [filter/api_response_body, transform/response_to_span]
exporters: [otlp_json]
traces/llm_response:
receivers: [otlp_json]
processors: [batch]
exporters: [otlp_http/langfuse]
The filter drops every log except response bodies that carry trace context. The other log events, including the large api_request_body, never leave the collector. The new span’s parent is the log’s span (the turn), and its ID is the first 16 hex characters of a SHA-256 of request_id, so a resent log produces the same span rather than a duplicate.
The span is written as an OTTL map literal, and String() turns it into JSON. That’s not obvious: OTTL has ParseJSON but no ToJSON, and String() is documented as a type conversion. It does serialize maps and slices to JSON, though, escaping the reply body properly along the way. I learned that from an open request to add ToJSON, where a maintainer’s first reply was “Doesn’t the String function already accomplish this?” My first version built the JSON by hand with Format and Go’s %q quoting, which works until a reply contains a control character that %q escapes differently from JSON.
The result: each turn now has claude_code.llm_response observations whose Output is the full response. A few things to know:
- A response shows up after the tool call it triggered, not right after its request. Claude Code emits the log once the tool has run, and the log timestamp is the only time the collector has. Pair them by
request_id. - Thinking still arrives as
"thinking":"<REDACTED>". OTEL_LOG_ASSISTANT_RESPONSES=1emits a lighterassistant_responselog event: just the reply text in aresponseattribute, with the same trace context andrequest_id. I bridged the raw body anyway. A call that ends in a tool call has no text, so it produces noassistant_responseevent, and the raw body also has thetool_useblocks andstop_reason.- Langfuse types these as generations, probably because of the
modelattribute. They carry no usage, so nothing is counted twice.
OTel vs. the plugin
I installed the plugin next to this setup and sent both into the same project to compare. The short version:
- Native OTel plus the collector: live, structural, and cheap. You get prompts, tool calls with inputs and outputs, tokens, cost, timing, permission waits, and request IDs. With the logs bridge you also get the model’s replies, as sibling spans. You don’t get thinking, or the full message history the model was sent. That’s in
api_request_bodyand could be bridged the same way, but it repeats the whole conversation on every call. - The Langfuse plugin: full conversation text, including every message the model was sent and the git branch, rebuilt from the transcript. It arrives one turn late and fails silently if a key is wrong.
The full comparison, the plugin’s gotchas, and how to roll it out in a shared dev image behind an egress proxy are in the next post.
A few other notes
- Langfuse v4 stores these spans in ClickHouse’s
events_fulltable, not the olderobservationsandtracestables. If you go looking with SQL and find zero rows, look there. - The OTel spans carry your Claude account email and IDs as metadata. That’s fine locally. Think about it before pointing this at a shared Langfuse. The plugin sends a user only if you set
LANGFUSE_USER_ID, but it does send full conversation text. - Langfuse also has an AI Gateway route that records every model call. It needs an Anthropic API key, though, not a Claude subscription login.
Claude Code and Opus 5.5 were instrumental in investigating functionality and drafting this post.
Copyright 2026 Wendy Smoak - This post first appeared on wsmoak.net and is CC BY-NC licensed.