Observability with OpenTelemetry
기준일: 2026-07-26
공식 기준: Observability with OpenTelemetry
Observability with OpenTelemetry 문서는 Claude Code 공식 문서(agent-sdk/observability)를 한국어로 정리한 가이드입니다. Export traces, metrics, and events from the Agent SDK to your observability backend using OpenTelemetry. 명령·설정 키·코드 예시는 공식 문서를 그대로 보존하며, 해석과 절차 안내는 한국어로 제공합니다. 최종 동작은 설치 버전과 공식 원문을 확인하세요.
핵심 요약
Export traces, metrics, and events from the Agent SDK to your observability backend using OpenTelemetry.
한국어 가이드 범위: agent-sdk/observability 경로의 설정·명령·제약·예시를 학습용으로 재구성합니다.
문서 구성
공식 문서의 주요 섹션은 다음과 같습니다.
- Observability with OpenTelemetry
- How telemetry flows from the SDK
- Enable telemetry export
- Flush telemetry from short-lived calls
- Read agent traces
- Link traces to your application
- Tag telemetry from your agent
- Attribute actions to your end users
- Control sensitive data in exports
- Related documentation
상세 내용
Observability with OpenTelemetry
Export traces, metrics, and events from the Agent SDK to your observability backend using OpenTelemetry.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
주요 항목:
- which tools they called
- how long each model request took
- how many tokens were spent
- where failures occurred
How telemetry flows from the SDK
The Agent SDK runs the Claude Code CLI as a child process and communicates with it over a local pipe. The CLI has OpenTelemetry instrumentation built in: it records spans around each model request and tool execution, emits metrics for token and cost counters, and emits structured log events for prompts and tool results. The SDK does not produce telemetry of its own. Instead, it passes configuration through to the CLI process, and the CLI exports directly to your collector.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
주요 항목:
- Process environment: set the variables in your shell, container, or orchestrator before your application starts. Every
query()call picks them up automatically with no code change. This is the recommended approach for production deployments. - Per-call options: set the variables in
ClaudeAgentOptions.env(Python) oroptions.env(TypeScript). Use this when different agents in the same process need different telemetry settings. In Python,envis merged on top of the inherited environment. In TypeScript,envreplaces the inherited environment entirely, so include...process.envin the object you pass.
| Signal | What it contains | Enable with |
|---|---|---|
| Metrics | Counters for tokens, cost, sessions, lines of code, and tool decisions | OTEL_METRICS_EXPORTER |
| Log events | Structured records for each prompt, API request, API error, and tool result | OTEL_LOGS_EXPORTER |
| Traces | Spans for each interaction, model request, tool call, and hook (beta) | OTEL_TRACES_EXPORTER plus CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1 |
Enable telemetry export
Telemetry is off until you set CLAUDE_CODE_ENABLE_TELEMETRY=1 and choose at least one exporter. The most common configuration sends all three signals over OTLP HTTP to a collector.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Flush telemetry from short-lived calls
The CLI batches telemetry and exports on an interval. On a clean process exit it attempts to flush pending data, but the flush is bounded by a short timeout, so spans can still be dropped if the collector is slow to respond. If your process is killed before the CLI shuts down, anything still in the batch buffer is lost. Lowering the export intervals reduces both windows.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Read agent traces
Traces give you the most detailed view of an agent run. With CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1 set, each step of the agent loop becomes a span you can inspect in your tracing backend:
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
주요 항목:
claude_code.interaction: wraps a single turn of the agent loop, from receiving a prompt to producing a response.claude_code.llm_request: wraps each call to the Claude API, with model name, latency, and token counts as attributes.claude_code.tool: wraps each tool invocation, with child spans for the permission wait (claude_code.tool.blocked_on_user) and the execution itself (claude_code.tool.execution).claude_code.hook: wraps each hook execution. Requires detailed beta tracing (ENABLE_BETA_TRACING_DETAILED=1andBETA_TRACING_ENDPOINT) in addition to the variables above.
Link traces to your application
The SDK automatically propagates W3C trace context into the CLI subprocess. When you call query() while an OpenTelemetry span is active in your application, the SDK injects TRACEPARENT and TRACESTATE into the child process environment, and the CLI reads them so its claude_code.interaction span becomes a child of your span. The agent run then appears inside your application's trace instead of as a disconnected root.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Tag telemetry from your agent
By default, the CLI reports service.name as claude-code. If you run several agents, or run the SDK alongside other services that export to the same collector, override the service name and add resource attributes so you can filter by agent in your backend.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Attribute actions to your end users
The CLI attaches identity attributes to every event based on the credential it uses to call Anthropic. When you build an application that serves many end users from one deployment, these attributes identify your service's credential, not the end user on whose behalf the agent acted.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
Control sensitive data in exports
Telemetry is structural by default. Durations, model names, and tool names are recorded on every span; token counts are recorded when the underlying API request returns usage data, so spans for failed or aborted requests may omit them. The content your agent reads and writes is not recorded by default. These opt-in variables add content to the exported data:
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
| Variable | Adds |
|---|---|
OTEL_LOG_USER_PROMPTS=1 |
Prompt text on claude_code.user_prompt events and on the claude_code.interaction span |
OTEL_LOG_TOOL_DETAILS=1 |
Tool input arguments (file paths, shell commands, search patterns) on claude_code.tool_result events |
OTEL_LOG_TOOL_CONTENT=1 |
Full tool input and output bodies as span events on claude_code.tool, truncated at 60 KB by default, configurable via CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH, {/* min-version: 2.1.214 */}which requires Claude Code v2.1.214 or later. Requires tracing to be enabled |
OTEL_LOG_RAW_API_BODIES |
Full Anthropic Messages API request and response JSON as claude_code.api_request_body and claude_code.api_response_body log events. Set to 1 for inline bodies truncated at 60 KB by default, or file:<dir> for untruncated bodies on disk with a body_ref path in the event. CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH configures the inline truncation limit, {/* min-version: 2.1.214 */}and requires Claude Code v2.1.214 or later. Bodies include the entire conversation history and have extended-thinking content redacted. Enabling this implies consent to everything the three variables above would reveal |
Related documentation
These guides cover adjacent topics for monitoring and deploying agents:
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문을 확인하세요.
주요 항목:
- Track cost and usage: read token and cost data from the message stream without an external backend.
- Hosting the Agent SDK: deploy agents in containers where you can set OpenTelemetry variables at the environment level.
- Monitoring: the complete reference for every environment variable, metric, and event the CLI emits.
실습 체크리스트
- 공식 문서와 로컬/SDK 버전을 대조합니다.
- 관련 CLI·SDK 옵션은 공식 페이지와
--help로 교차 확인합니다. - Agent SDK 예시는 TypeScript/Python 패키지 최신 API를 우선합니다.
- 권한·호스팅·보안 설정 변경 후 통합 테스트를 실행합니다.
자주 쓰는 명령·설정 예시
Because the child process inherits your application's environment by default, you can achieve the same result by exporting these variables in a Dockerfile, Kubernetes manifest, or shell profile and omitting `options.env` entirely.
The `console` exporter writes telemetry to standard output, which the SDK uses
as its message channel. Do not set `console` as an exporter value when running
through the SDK. To inspect telemetry locally, point
`OTEL_EXPORTER_OTLP_ENDPOINT` at a local collector or an all-in-one Jaeger
container instead.
### Flush telemetry from short-lived calls
The CLI batches telemetry and exports on an interval. On a clean process exit it attempts to flush pending data, but the flush is bounded by a short timeout, so spans can still be dropped if the collector is slow to respond. If your process is killed before the CLI shuts down, anything still in the batch buffer is lost. Lowering the export intervals reduces both windows.
By default, metrics export every 60 seconds and traces and logs export every 5 seconds. The following example shortens all three intervals so that data reaches the collector while a short task is still running:
## Read agent traces
Traces give you the most detailed view of an agent run. With `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1` set, each step of the agent loop becomes a span you can inspect in your tracing backend:
* **`claude_code.interaction`:** wraps a single turn of the agent loop, from receiving a prompt to producing a response.
* **`claude_code.llm_request`:** wraps each call to the Claude API, with model name, latency, and token counts as attributes.
* **`claude_code.tool`:** wraps each tool invocation, with child spans for the permission wait (`claude_code.tool.blocked_on_user`) and the execution itself (`claude_code.tool.execution`).
* **`claude_code.hook`:** wraps each [hook](/docs/en/agent-sdk/hooks) execution. Requires detailed beta tracing (`ENABLE_BETA_TRACING_DETAILED=1` and `BETA_TRACING_ENDPOINT`) in addition to the variables above.
The `llm_request`, `tool`, and `hook` spans are children of the enclosing `claude_code.interaction` span. When the agent spawns a subagent through the Task tool, the subagent's `llm_request` and `tool` spans nest under the parent agent's `claude_code.tool` span, so the full delegation chain appears as one trace.
Spans carry a `session.id` attribute by default. When you make several `query()` calls against the same [session](/docs/en/agent-sdk/sessions), filter on `session.id` in your backend to see them as one timeline. The attribute is omitted if `OTEL_METRICS_INCLUDE_SESSION_ID` is set to a falsy value.
Tracing is in beta. Span names and attributes may change between releases. See
[Traces (beta)](/docs/en/monitoring-usage#traces-beta) in the Monitoring reference
for the trace exporter configuration variables.
## Link traces to your application
The SDK automatically propagates W3C trace context into the CLI subprocess. When you call `query()` while an OpenTelemetry span is active in your application, the SDK injects `TRACEPARENT` and `TRACESTATE` into the child process environment, and the CLI reads them so its `claude_code.interaction` span becomes a child of your span. The agent run then appears inside your application's trace instead of as a disconnected root.
OTLP event log records emitted during the run carry the same trace context: with `TRACEPARENT` set, each record's `trace_id` and `span_id` match your application's trace, so you can join [events](/docs/en/monitoring-usage#events) to spans in your backend. {/* min-version: 2.1.212 */}Before v2.1.212, event records emitted outside an active span didn't carry `trace_id` or `span_id`.
When trace-context propagation is enabled, the CLI also forwards `TRACEPARENT` to every Bash and PowerShell command it runs. If a command launched through the Bash tool emits its own OpenTelemetry spans, those spans nest under the `claude_code.tool.execution` span that wraps the command.
Auto-injection is skipped when you set `TRACEPARENT` explicitly in `options.env`, so you can pin a specific parent context if needed. Interactive CLI sessions ignore inbound `TRACEPARENT` entirely; only Agent SDK and `claude -p` runs honor it. See [Traces (beta)](/docs/en/monitoring-usage#traces-beta) in the Monitoring reference for the full span and attribute reference.
## Tag telemetry from your agent
By default, the CLI reports `service.name` as `claude-code`. If you run several agents, or run the SDK alongside other services that export to the same collector, override the service name and add resource attributes so you can filter by agent in your backend.
The following example renames the service and attaches deployment metadata. These values are applied as OpenTelemetry resource attributes on every span, metric, and event the agent emits:
## Attribute actions to your end users
The CLI attaches [identity attributes](/docs/en/monitoring-usage#standard-attributes) to every event based on the credential it uses to call Anthropic. When you build an application that serves many end users from one deployment, these attributes identify your service's credential, not the end user on whose behalf the agent acted.
To make tool calls and MCP activity attributable to your application's end users, inject end-user identity as resource attributes on each `query()` call. Percent-encode values before interpolating them, since `OTEL_RESOURCE_ATTRIBUTES` [reserves commas, spaces, and equals signs](/docs/en/monitoring-usage#multi-team-organization-support). The following example attaches the requesting user and tenant to every span and event from one request. It assumes a `request` object from your web framework carrying the user and tenant IDs:
관련 링크
- 공식 원문: agent-sdk/observability
- 문서 홈
이 가이드는 공식 문서를 한국어 학습용으로 재구성한 것입니다. 옵션 기본값·API 이름은 설치 버전에 따라 달라질 수 있습니다.