---
title: 搭配 Claude API 使用 OpenTelemetry
url: https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry/api
description: 在 Claude Console 中新增目的地，將您的 Messages API 請求與 Managed Agents 工作階段的 OpenTelemetry 追蹤資料傳送至您的可觀測性平台。
featureMetadata:
  topic:
    title: OpenTelemetry
    url: https://platform.claude.com/docs/en/manage-claude/opentelemetry
  status: beta
  zdr:
    eligibility: eligible
    note: Excludes [Covered Models](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements). 僅適用於本身符合 ZDR 資格的功能，例如 Messages API。Claude Managed Agents 不符合 ZDR 資格。
  supportedPlatforms:
    Claude API: beta
    Claude Platform on AWS: beta
  rows:
    - label: 適用於
      value: Messages API, Claude Managed Agents
  details:
    - 傳送之後，資料將由您選擇的服務在 Anthropic 外部保存，並受該服務的保留與存取控制規範。
---

透過 OpenTelemetry，Claude API 可以為其執行的每個模型請求與每次工具使用發出一個「*Span*」（跨度）。您無需變更程式碼，即可在您的可觀測性平台中檢視這些 span。

API 會為您的 Messages API 請求與 Managed Agents 工作階段發出 span。若要接收它們，請在 Claude Console 中新增一個「*destination*」（目的地）。目的地會告訴 API 您的可觀測性平台的 OTLP 端點以及如何向其進行驗證。

## 您需要準備的項目

* **管理員角色**：位於 Claude Console 組織中，用於新增和變更目的地。擁有開發者角色時，您可以檢視目的地。如果您的組織使用 Claude Platform on AWS，請依照[登入](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws#signing-in)中的說明，透過 AWS Console 登入 Console。
* 一個 **OTLP/HTTP 端點**，可在連接埠 443 的 HTTPS URL 上接受 protobuf 編碼。如果您自行執行 [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/)，其 OTLP/HTTP 接收器預設監聽連接埠 4318。請將接收器設定為在連接埠 443 上接受 HTTPS，或在 Collector 前方放置負載平衡器或反向代理。
* **端點的憑證**，例如 API 金鑰。

## 1. 新增目的地

<Info>
  當您新增遙測目的地時，Anthropic 會依據您的供應商條款與存取控制，將您組織中 Claude Platform 活動的追蹤傳送至您指定的第三方供應商 OTLP/HTTP 端點。傳送之後，資料將由您選擇的服務在 Anthropic 外部保存，並受該服務的保留與存取控制規範。
</Info>

1. 在 Console 中，開啟您組織的 [OpenTelemetry 設定頁面](https://platform.claude.com/settings/telemetry-destinations)，然後點擊 **Add destination**。

2. 設定目的地：

   | 欄位                             | 輸入內容                                                                                                                                                                                                                                                          |
   | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
   | **Provider**                   | 您的可觀測性平台；如果未列出，請選擇 **Custom**。如果您選擇已列出的平台，Console 會要求您提供其詳細資訊（例如 API 金鑰），而非 **OTLP endpoint URL**、**Request headers** 和 **OTLP traces endpoint URL**。                                                                                                         |
   | **Name**                       | 選填。例如「Acme 的可觀測性平台」。                                                                                                                                                                                                                                          |
   | **OTLP endpoint URL**          | 您的可觀測性平台 OTLP/HTTP 端點的基礎 HTTPS URL，需使用主機名稱而非 IP 位址。它可以包含路徑前綴，例如 `https://gateway.example.com/otlp`。請勿加上 `/v1/traces`，因為 API 會自動加上它。如果您設定了 **OTLP traces endpoint URL**，API 則會改用該 URL。                                                                         |
   | **Request headers**            | API 隨每個請求傳送的標頭，例如您的可觀測性平台的 API 金鑰標頭。請只將憑證放在標頭值中。儲存後，Console 不會再次顯示這些值。                                                                                                                                                                                        |
   | **Content mode**               | **Metadata only** 或 **Full content**。請參閱[內容模式的差異](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry#choose-a-content-mode)。                                                                                                                  |
   | **Workspaces**                 | 目的地接收其 span 的工作區：**All**、**Selected** 或 **All except**。請參閱[為目的地選擇工作區](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry/api#choose-workspaces-for-a-destination)。                                                                            |
   | **OTLP traces endpoint URL**   | 選填，位於 **Advanced settings** 下。您的可觀測性平台追蹤端點的完整 URL，例如 `https://gateway.example.com/custom/traces`。當該平台在 OTLP endpoint URL 加上 `/v1/traces` 以外的 URL 接收追蹤時，請設定此項。它必須與 OTLP endpoint URL 使用相同的主機。                                                                  |
   | **Maximum content size in MB** | 選填，當內容模式為 **Full content** 時，位於 **Advanced settings** 下。API 在每個 span 中傳送的內容上限。Console 會根據您選擇的 **Provider** 填入此值。請依您的可觀測性平台可接受的大小進行變更。若將此欄位留空，則會傳送 API 所允許的最大內容量。請參閱[內容限制](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry#content-limits)。 |

3. 點擊 **Add destination** 以儲存。

4. 請在該目的地的 **More actions** 選單中點擊 **Test**。接著會顯示一則訊息，說明測試 span 已傳送至您的收集器，或傳送失敗的原因（請參閱[傳送錯誤](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry/api#delivery-errors)）。

5. 請確認您的可觀測性平台已收到 `anthropic.test` span。

### Admin API 與 CLI

您也可以透過 [Admin API](https://platform.claude.com/docs/zh-TW/manage-claude/admin-api) 新增目的地，而不必使用 Console。請以管理員身分登入 CLI，或在 `ANTHROPIC_API_KEY` 中使用 [Admin API 金鑰](https://platform.claude.com/docs/zh-TW/manage-claude/admin-api-keys)。在 Claude Platform on AWS 上，請改為將請求傳送至 `https://aws-external-anthropic.{region}.api.aws`，並依照[發出請求](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws#making-requests)中的說明，使用您的 AWS 憑證簽署。在此情況下，您的 [IAM 政策](https://platform.claude.com/docs/zh-TW/api/claude-platform-on-aws-iam-actions)決定誰可以管理目的地。請求只能包含您的 AWS 帳戶在該區域中的工作區。

<CodeGroup>
  ```bash CLI
  # Sign in once as an admin, which opens a browser. Leave ANTHROPIC_API_KEY unset, because it overrides the profile.
  ant auth login --profile admin --scope "org:admin"
  ant --profile admin beta:organization:telemetry-destinations create \
    --endpoint-url https://gateway.example.com/otlp \
    --headers '{authorization: "Bearer YOUR_OBSERVABILITY_API_KEY"}' \
    --traces.content-mode metadata_only \
    --workspaces.type all
  ```

  ```bash cURL
  curl --fail-with-body -sS "https://api.anthropic.com/v1/organizations/telemetry_destinations" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "anthropic-beta: telemetry-destinations-2026-08-11" \
    -H "content-type: application/json" \
    -d '{
      "endpoint_url": "https://gateway.example.com/otlp",
      "headers": {"authorization": "Bearer YOUR_OBSERVABILITY_API_KEY"},
      "traces": {"content_mode": "metadata_only"},
      "workspaces": {"type": "all"}
    }'
  ```

  ```python Python
  client = anthropic.Anthropic()

  destination = client.beta.organization.telemetry_destinations.create(
      endpoint_url="https://gateway.example.com/otlp",
      headers={"authorization": "Bearer YOUR_OBSERVABILITY_API_KEY"},
      traces={"content_mode": "metadata_only"},
      workspaces={"type": "all"},
  )

  print(destination.id)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const destination = await client.beta.organization.telemetryDestinations.create({
    endpoint_url: "https://gateway.example.com/otlp",
    headers: { authorization: "Bearer YOUR_OBSERVABILITY_API_KEY" },
    traces: { content_mode: "metadata_only" },
    workspaces: { type: "all" }
  });

  console.log(destination.id);
  ```

  ```csharp C#
  using Anthropic.Models.Beta.Organization.TelemetryDestinations;

  AnthropicClient client = new();

  var destination = await client.Beta.Organization.TelemetryDestinations.Create(
      new()
      {
          EndpointUrl = "https://gateway.example.com/otlp",
          Headers = new Dictionary<string, string>
          {
              ["authorization"] = "Bearer YOUR_OBSERVABILITY_API_KEY",
          },
          Traces = new() { ContentMode = BetaTelemetryDestinationContentMode.MetadataOnly },
          Workspaces = new BetaTelemetryDestinationWorkspacesAllParams(),
      }
  );

  Console.WriteLine(destination.ID);
  ```

  ```go Go
  client := anthropic.NewClient()

  destination, err := client.Beta.Organization.TelemetryDestinations.New(
  	context.Background(),
  	anthropic.BetaOrganizationTelemetryDestinationNewParams{
  		EndpointURL: "https://gateway.example.com/otlp",
  		Headers: map[string]string{
  			"authorization": "Bearer YOUR_OBSERVABILITY_API_KEY",
  		},
  		Traces: anthropic.BetaTelemetryDestinationTracesParams{
  			ContentMode: anthropic.BetaTelemetryDestinationContentModeMetadataOnly,
  		},
  		Workspaces: anthropic.BetaTelemetryDestinationWorkspacesParamsUnion{
  			OfAll: &anthropic.BetaTelemetryDestinationWorkspacesAllParams{},
  		},
  	},
  )
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(destination.ID)
  ```

  ```java Java
  import com.anthropic.core.JsonValue;
  import com.anthropic.models.beta.organization.telemetrydestinations.BetaTelemetryDestinationContentMode;
  import com.anthropic.models.beta.organization.telemetrydestinations.BetaTelemetryDestinationTracesParams;
  import com.anthropic.models.beta.organization.telemetrydestinations.BetaTelemetryDestinationWorkspacesAllParams;
  import com.anthropic.models.beta.organization.telemetrydestinations.TelemetryDestinationCreateParams;

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      var params = TelemetryDestinationCreateParams.builder()
          .endpointUrl("https://gateway.example.com/otlp")
          .headers(TelemetryDestinationCreateParams.Headers.builder()
              .putAdditionalProperty("authorization", JsonValue.from("Bearer YOUR_OBSERVABILITY_API_KEY"))
              .build())
          .traces(BetaTelemetryDestinationTracesParams.builder()
              .contentMode(BetaTelemetryDestinationContentMode.METADATA_ONLY)
              .build())
          .workspaces(BetaTelemetryDestinationWorkspacesAllParams.builder().build())
          .build();
      var destination = client.beta().organization().telemetryDestinations().create(params);

      IO.println(destination.id());
  }
  ```

  ```php PHP
  $client = new Client();

  $destination = $client->beta->organization->telemetryDestinations->create(
      endpointURL: 'https://gateway.example.com/otlp',
      headers: ['authorization' => 'Bearer YOUR_OBSERVABILITY_API_KEY'],
      traces: ['contentMode' => 'metadata_only'],
      workspaces: ['type' => 'all'],
  );

  echo "{$destination->id}\n";
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  destination = client.beta.organization.telemetry_destinations.create(
    endpoint_url: "https://gateway.example.com/otlp",
    headers: {authorization: "Bearer YOUR_OBSERVABILITY_API_KEY"},
    traces: {content_mode: :metadata_only},
    workspaces: {type: :all}
  )

  puts destination.id
  ```
</CodeGroup>

建立請求接受 Console 中除 **Provider** 以外的設定，因此請自行輸入您可觀測性平台的端點 URL 與標頭。請以位元組為單位設定 `traces.max_content_bytes` (csharp, go: `Traces.MaxContentBytes`; java, php: `traces.maxContentBytes`)，以符合您可觀測性平台可接受的大小（請參閱[內容限制](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry#content-limits)）。若要列出、變更或刪除目的地，或新增或移除單一工作區，請使用遙測目的地 API 的其他方法。

## 2. 為目的地選擇工作區

目的地會接收其涵蓋之工作區的 span。請在新增目的地時選擇這些工作區。在 **Workspaces** 中，選擇下列其中一項：

* **All：** 組織中的每個工作區，包括 [Default Workspace](https://platform.claude.com/docs/zh-TW/manage-claude/workspaces#how-workspaces-work) 以及之後建立的工作區。
* **Selected：** 僅限您選擇的工作區。
* **All except：** 與 **All** 相同，但不包括您選擇的工作區。

若選擇 **Selected** 或 **All except**，請在選項下方出現的搜尋方塊中選擇工作區。若之後要變更目的地的工作區，請在 **Workspace** 篩選器顯示 **All** 時，於 [OpenTelemetry 設定頁面](https://platform.claude.com/settings/telemetry-destinations)上開啟該目的地的 **More actions** 選單。點擊 **Edit**，然後選擇另一個 **Workspaces** 選項，或在搜尋方塊中變更工作區。

如果您在組織中擁有開發者角色，並在某個工作區中擁有 Workspace Admin 角色，就可以將該工作區新增至 **Selected** 目的地，或將其從該目的地移除。請將 **Workspace** 篩選器設定為該工作區，然後開啟該目的地的 **More actions** 選單。在 Claude Platform on AWS 上，Console 沒有 Workspace Admin 角色。在該平台上，由您的 [IAM 政策](https://platform.claude.com/docs/zh-TW/api/claude-platform-on-aws-iam-actions)決定誰可以將工作區新增至目的地或將其從目的地移除。

API 會將 span 傳送至每個涵蓋[請求或工作階段執行所在工作區](https://platform.claude.com/docs/zh-TW/manage-claude/workspaces#api-keys-and-resource-scoping)的已啟用目的地。

## 3. 確認 span 已送達

1. 在 Console 中，選取該目的地所涵蓋的工作區，並在 [playground](https://platform.claude.com/playground) 中傳送一個 Messages API 請求。您也可以從您的應用程式傳送 Messages API 請求，或在該工作區中啟動一個 Managed Agents 工作階段。若要啟動工作階段，您可以依照[開始使用 Claude Managed Agents](https://platform.claude.com/docs/zh-TW/managed-agents/quickstart) 中的步驟操作。
2. 在 Console 的 [OpenTelemetry 設定頁面](https://platform.claude.com/settings/telemetry-destinations)上，確認該目的地的 **Delivery** 欄顯示 **Healthy**。這可能需要約一分鐘。
3. 在您的可觀測性平台中，篩選 `service.name` = `claude-platform` 以找到該請求的 span。

如果該欄顯示 **Failing**，請將指標停留在其上以查看最後一次錯誤。若要找出可能的原因，請參閱[傳送錯誤](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry/api#delivery-errors)。

## 4. 將 API span 連接到您自己的追蹤

預設情況下，Messages API 請求或 Managed Agents 工作階段的 API span 位於各自獨立的追蹤中。請將它們連接到您應用程式的追蹤，使其巢狀於您自己的 span 之下。

API 會從 W3C [`traceparent` 標頭](https://www.w3.org/TR/trace-context/)讀取每個請求的追蹤上下文。如果標頭中的取樣旗標為關閉，API 就不會發出該請求的 span 或其下的 span。Claude Platform on AWS 尚不支援此標頭。您傳送至 Claude Platform on AWS 的請求，其 span 一律會開始各自獨立的追蹤，即使取樣旗標為關閉亦然。

<Tabs>
  <Tab title="使用 Claude SDK">
    若要連接 API span，請在您的應用程式中[設定 SDK 追蹤](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry/sdk)，並在您自己的某個 span 內呼叫 SDK。這樣您的 span 就會包含 SDK span，而 SDK span 又包含 API span。請將所有這些 span 傳送到同一個可觀測性平台，使其能將它們顯示為單一追蹤。請參閱[Messages API 請求](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry#a-messages-api-request)與 [Managed Agents 工作階段](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry#a-managed-agents-session)的範例追蹤。

    以下範例在您自己的 span 內向工作階段傳送一則使用者訊息：

    <CodeGroup exclude="shell">
      ```python Python
      from opentelemetry import trace

      tracer = trace.get_tracer("my-service")

      with tracer.start_as_current_span("summarize_issues"):
          client.beta.sessions.events.send(
              session.id,
              events=[
                  {
                      "type": "user.message",
                      "content": [{"type": "text", "text": "Summarize the open issues"}],
                  },
              ],
          )
      ```

      ```typescript TypeScript
      import { trace } from "@opentelemetry/api";

      const tracer = trace.getTracer("my-service");

      await tracer.startActiveSpan("summarize_issues", async (span) => {
        try {
          await client.beta.sessions.events.send(session.id, {
            events: [
              {
                type: "user.message",
                content: [{ type: "text", text: "Summarize the open issues" }]
              }
            ]
          });
        } finally {
          span.end();
        }
      });
      ```

      ```csharp C#
      using System.Diagnostics;

      // 將此來源加入您的 tracer provider，與 com.anthropic.sdk.csharp 並列。
      var source = new ActivitySource("MyService");

      using (source.StartActivity("summarize_issues"))
      {
          // parameters 包含一個 user.message 事件。
          await client.Beta.Sessions.Events.Send(session.ID, parameters);
      }
      ```

      ```go Go
      // 傳入包含您的 span 的 context。
      ctx, span := otel.Tracer("my-service").Start(ctx, "summarize_issues")
      defer span.End()

      // params 包含一個 user.message 事件。
      _, err := client.Beta.Sessions.Events.Send(ctx, session.ID, params)
      ```

      ```java Java
      Tracer tracer = GlobalOpenTelemetry.getTracer("my-service");
      Span span = tracer.spanBuilder("summarize_issues").startSpan();

      try (Scope scope = span.makeCurrent()) {
          // params 包含一個 user.message 事件。
          client.beta().sessions().events().send(session.id(), params);
      } finally {
          span.end();
      }
      ```

      ```php PHP
      use OpenTelemetry\API\Globals;

      $tracer = Globals::tracerProvider()->getTracer('my-service');
      $span = $tracer->spanBuilder('summarize_issues')->startSpan();
      $scope = $span->activate();

      try {
          $client->beta->sessions->events->send(
              $session->id,
              events: [
                  [
                      'type' => 'user.message',
                      'content' => [
                          ['type' => 'text', 'text' => 'Summarize the open issues'],
                      ],
                  ],
              ],
          );
      } finally {
          $scope->detach();
          $span->end();
      }
      ```

      ```ruby Ruby
      tracer = OpenTelemetry.tracer_provider.tracer("my-service")

      tracer.in_span("summarize_issues") do
        client.beta.sessions.events.send_(
          session.id,
          events: [
            {
              type: "user.message",
              content: [{type: "text", text: "Summarize the open issues"}]
            }
          ]
        )
      end
      ```
    </CodeGroup>

    SDK 會使用您應用程式的 propagator 寫入 `traceparent` 標頭，其中的取樣旗標會依循您的取樣器。如果您的應用程式使用 W3C trace context 以外的 propagator（例如 B3），請同時加入 W3C trace context propagator。
  </Tab>

  <Tab title="使用其他用戶端">
    將目前 span 的追蹤上下文複製到請求標頭中，例如在您建立 Managed Agents 工作階段或傳送使用者訊息時：

    <CodeGroup exclude="shell:CLI">
      ```bash cURL
      # TRACEPARENT 是您自身服務中作用中 span 的 traceparent，
      # 例如 00-<trace-id>-<span-id>-01。
      curl -fsSL "https://api.anthropic.com/v1/sessions/$SESSION_ID/events" \
        -H "x-api-key: $ANTHROPIC_API_KEY" \
        -H "anthropic-version: 2023-06-01" \
        -H "anthropic-beta: managed-agents-2026-04-01" \
        -H "content-type: application/json" \
        -H "traceparent: $TRACEPARENT" \
        -d '{
          "events": [
            {
              "type": "user.message",
              "content": [{"type": "text", "text": "Summarize the open issues"}]
            }
          ]
        }'
      ```

      ```python Python
      import os
      import httpx2
      from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator

      headers = {
          "x-api-key": os.environ["ANTHROPIC_API_KEY"],
          "anthropic-version": "2023-06-01",
          "anthropic-beta": "managed-agents-2026-04-01",
          "content-type": "application/json",
      }
      # 將作用中 span 的追蹤上下文複製到請求標頭中。
      TraceContextTextMapPropagator().inject(headers)

      httpx2.post(
          f"https://api.anthropic.com/v1/sessions/{os.environ['SESSION_ID']}/events",
          headers=headers,
          json={
              "events": [
                  {
                      "type": "user.message",
                      "content": [{"type": "text", "text": "Summarize the open issues"}],
                  },
              ],
          },
      )
      ```

      ```typescript TypeScript
      import { context, defaultTextMapSetter } from "@opentelemetry/api";
      import { W3CTraceContextPropagator } from "@opentelemetry/core";

      const headers: Record<string, string> = {
        "x-api-key": process.env.ANTHROPIC_API_KEY!,
        "anthropic-version": "2023-06-01",
        "anthropic-beta": "managed-agents-2026-04-01",
        "content-type": "application/json"
      };
      // 將作用中 span 的追蹤上下文（trace context）複製到請求標頭中。
      new W3CTraceContextPropagator().inject(context.active(), headers, defaultTextMapSetter);

      await fetch(`https://api.anthropic.com/v1/sessions/${process.env.SESSION_ID}/events`, {
        method: "POST",
        headers,
        body: JSON.stringify({
          events: [
            {
              type: "user.message",
              content: [{ type: "text", text: "Summarize the open issues" }]
            }
          ]
        })
      });
      ```

      ```csharp C#
      using System.Diagnostics;
      using System.Net.Http.Json;
      using OpenTelemetry;
      using OpenTelemetry.Context.Propagation;

      using var httpClient = new HttpClient();
      using var request = new HttpRequestMessage(
          HttpMethod.Post,
          $"https://api.anthropic.com/v1/sessions/{Environment.GetEnvironmentVariable("SESSION_ID")}/events")
      {
          // JsonContent 會設定 content-type 標頭。
          Content = JsonContent.Create(new
          {
              events = new[]
              {
                  new
                  {
                      type = "user.message",
                      content = new[] { new { type = "text", text = "Summarize the open issues" } },
                  },
              },
          }),
      };
      request.Headers.Add("x-api-key", Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY"));
      request.Headers.Add("anthropic-version", "2023-06-01");
      request.Headers.Add("anthropic-beta", "managed-agents-2026-04-01");

      // 將作用中 span 的追蹤上下文（trace context）複製到請求標頭中。
      new TraceContextPropagator().Inject(
          new PropagationContext(Activity.Current?.Context ?? default, Baggage.Current),
          request,
          (carrier, key, value) => carrier.Headers.Add(key, value));

      await httpClient.SendAsync(request);
      ```

      ```go Go
      import (
      	"context"
      	"net/http"
      	"os"
      	"strings"

      	"go.opentelemetry.io/otel/propagation"
      )

      func sendMessage(ctx context.Context) error {
      	body := strings.NewReader(`{
      		"events": [
      			{
      				"type": "user.message",
      				"content": [{"type": "text", "text": "Summarize the open issues"}]
      			}
      		]
      	}`)
      	req, err := http.NewRequestWithContext(ctx, http.MethodPost,
      		"https://api.anthropic.com/v1/sessions/"+os.Getenv("SESSION_ID")+"/events", body)
      	if err != nil {
      		return err
      	}
      	req.Header.Set("x-api-key", os.Getenv("ANTHROPIC_API_KEY"))
      	req.Header.Set("anthropic-version", "2023-06-01")
      	req.Header.Set("anthropic-beta", "managed-agents-2026-04-01")
      	req.Header.Set("content-type", "application/json")

      	// 將作用中 span 的追蹤上下文（trace context）複製到請求標頭中。
      	propagation.TraceContext{}.Inject(ctx, propagation.HeaderCarrier(req.Header))

      	resp, err := http.DefaultClient.Do(req)
      	if err != nil {
      		return err
      	}
      	return resp.Body.Close()
      }
      ```

      ```java Java
      import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator;
      import io.opentelemetry.context.Context;
      import java.net.URI;
      import java.net.http.HttpClient;
      import java.net.http.HttpRequest;
      import java.net.http.HttpResponse;

      void main() throws Exception {
          var request = HttpRequest.newBuilder(URI.create(
                  "https://api.anthropic.com/v1/sessions/" + System.getenv("SESSION_ID") + "/events"))
              .header("x-api-key", System.getenv("ANTHROPIC_API_KEY"))
              .header("anthropic-version", "2023-06-01")
              .header("anthropic-beta", "managed-agents-2026-04-01")
              .header("content-type", "application/json")
              .POST(HttpRequest.BodyPublishers.ofString("""
                  {
                    "events": [
                      {
                        "type": "user.message",
                        "content": [{"type": "text", "text": "Summarize the open issues"}]
                      }
                    ]
                  }
                  """));

          // 將作用中 span 的追蹤上下文（trace context）複製到請求標頭中。
          W3CTraceContextPropagator.getInstance()
              .inject(Context.current(), request, HttpRequest.Builder::header);

          HttpClient.newHttpClient().send(request.build(), HttpResponse.BodyHandlers.ofString());
      }
      ```

      ```php PHP
      use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator;

      $headers = [
          'x-api-key' => getenv('ANTHROPIC_API_KEY'),
          'anthropic-version' => '2023-06-01',
          'anthropic-beta' => 'managed-agents-2026-04-01',
          'content-type' => 'application/json',
      ];
      // 將作用中 span 的 trace context（追蹤上下文）複製到請求標頭中。
      TraceContextPropagator::getInstance()->inject($headers);

      $ch = curl_init('https://api.anthropic.com/v1/sessions/' . getenv('SESSION_ID') . '/events');
      curl_setopt_array($ch, [
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_HTTPHEADER => array_map(
              static fn ($name, $value) => "$name: $value",
              array_keys($headers),
              $headers,
          ),
          CURLOPT_POSTFIELDS => json_encode([
              'events' => [
                  [
                      'type' => 'user.message',
                      'content' => [
                          ['type' => 'text', 'text' => 'Summarize the open issues'],
                      ],
                  ],
              ],
          ]),
      ]);
      curl_exec($ch);
      ```

      ```ruby Ruby
      require "json"
      require "net/http"
      require "opentelemetry"

      headers = {
        "x-api-key" => ENV.fetch("ANTHROPIC_API_KEY"),
        "anthropic-version" => "2023-06-01",
        "anthropic-beta" => "managed-agents-2026-04-01",
        "content-type" => "application/json"
      }
      # 將作用中 span 的追蹤上下文複製到請求標頭中。
      OpenTelemetry::Trace::Propagation::TraceContext.text_map_propagator.inject(headers)

      Net::HTTP.post(
        URI("https://api.anthropic.com/v1/sessions/#{ENV.fetch("SESSION_ID")}/events"),
        {
          events: [
            {
              type: "user.message",
              content: [{type: "text", text: "Summarize the open issues"}]
            }
          ]
        }.to_json,
        headers
      )
      ```
    </CodeGroup>
  </Tab>
</Tabs>

Messages API 也會在您透過 [MCP connector](https://platform.claude.com/docs/zh-TW/agents-and-tools/mcp-connector) 連接您的 MCP 伺服器時，將追蹤傳遞給該伺服器，讓它可以將自己的 span 放在 API span 之下。API 傳送給您的 MCP 伺服器的每個請求與通知，都會在 `params._meta` 中帶有 W3C `traceparent`。在 `tools/call` 請求中，它指向該次工具使用的 [`anthropic.mcp_tool_use`](https://platform.claude.com/docs/zh-TW/api/opentelemetry/spans#anthropic-tool-use-anthropic-mcp-tool-use-and-anthropic-custom-tool-use) span。在其他訊息中，它指向 [`anthropic.messages.create`](https://platform.claude.com/docs/zh-TW/api/opentelemetry/spans#anthropic-messages-create) span。對於 API 不追蹤的請求（例如 `traceparent` 標頭的取樣旗標為關閉的請求），API 不會傳送 `traceparent`。

## 後續步驟

<CardGroup cols={2}>
  <Card title="設定 SDK 追蹤" icon="code-brackets" href="https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry/sdk">
    取得用戶端的可觀測性。
  </Card>

  <Card title="查看範例追蹤" icon="sitemap" href="https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry#example-traces-and-how-to-read-them">
    追蹤一個請求從您的用戶端進入 Claude API 的過程。
  </Card>
</CardGroup>

## 傳送與健康狀態

以下規則適用於 API 傳送到您目的地的 span。

* **至少一次：** 目的地可能會多次收到同一個 span。若要移除重複項目，請使用 trace ID 與 span ID。
* **盡力而為：** span 可能在傳送前遺失。API 無法重新傳送遺失的 span。
* **壓縮：** API 會以 gzip 壓縮每次傳送的第一個請求，並設定標頭 `Content-Encoding: gzip`。如果您的端點以 `400` 或 `415` 回應該請求，API 會立即以未壓縮的方式再次傳送相同的 span。
* **重試：** 在逾時、連線、TLS 或 DNS 失敗，或收到 `408`、`429` 或 `5xx` 回應之後，API 會在稍後重試傳送，次數有限。API 不會重試其他失敗。
* **逾時：** 對於每個請求，您的端點必須在 5 秒內完成 TLS 交握，並在 5 秒內傳送回應標頭。每次傳送（包括不使用壓縮的重新傳送）總計在 10 秒後逾時。
* **User agent：** 每個請求都帶有標頭 `User-Agent: Claude-Platform`。

**Delivery** 欄會顯示每個目的地的狀態。該狀態最多可能延遲一分鐘。

| 傳送狀態         | 意義                                           |
| ------------ | -------------------------------------------- |
| **Healthy**  | 最後一次傳送成功。                                    |
| **Failing**  | 最後一次傳送失敗。若要查看錯誤，請將指標停留在 **Failing** 上。       |
| **No data**  | API 尚未嘗試傳送。                                  |
| **Disabled** | 該目的地不會接收 span。若要查看原因，請將指標停留在 **Disabled** 上。 |

在以下情況下，API 會停用目的地：

* 端點傳送 `3xx` 重新導向。
* 端點的主機名稱解析為非公開的 IP 位址。
* 所有傳送持續失敗達 24 小時。

API 不會將 span 傳送至已停用的目的地。若要重新開始匯出，請修正原因。接著，在 [OpenTelemetry 設定頁面](https://platform.claude.com/settings/telemetry-destinations)上的 **Workspace** 篩選器顯示 **All** 時，在該目的地的 **More actions** 選單中點擊 **Enable**。匯出會在大約一分鐘內重新開始。

若要變更目的地，請在 **Workspace** 篩選器顯示 **All** 時開啟其 **More actions** 選單。然後點擊 **Edit**、**Disable**、**Enable** 或 **Delete**。如果您變更了 **OTLP endpoint URL** 的主機，請重新輸入標頭值。如果該目的地有 **OTLP traces endpoint URL**，請為其設定相同的新主機，或將其清除。

## 限制

| 限制                    | 值          |
| --------------------- | ---------- |
| 每個組織的目的地數量（包括已停用的目的地） | 10         |
| 您為一個目的地選取的工作區數量       | 1,000      |
| 每個目的地的請求標頭數量          | 20         |
| 標頭名稱長度                | 128 位元組    |
| 標頭值長度                 | 4,096 位元組  |
| 所有標頭名稱和值的總長度          | 16,384 位元組 |
| 端點 URL 長度             | 2,048 個字元  |

## 疑難排解

| 問題                                     | 檢查項目                                                                                                                                                                                    |
| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 沒有 API span                            | 工作區需要一個涵蓋它且已啟用的目的地。請參閱[為目的地選擇工作區](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry/api#choose-workspaces-for-a-destination)。目的地開始涵蓋某個工作區後，來自該工作區的 span 最多可能需要一分鐘才會送達。 |
| **Delivery** 欄顯示 **Failing**           | 將指標停留在其上以查看最後一個錯誤。若要找出可能的原因，請參閱[傳遞錯誤](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry/api#delivery-errors)。                                                          |
| **Delivery** 欄顯示 **Disabled**          | 將指標停留在其上以查看原因。關於原因，請參閱[API 何時會停用目的地](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry/api#delivery-and-health)。                                                       |
| span 沒有提示或回應，但目的地已設定為 **Full content** | 您的組織可能與 Anthropic 之間有 HIPAA、FERPA 或 K-12 資料處理限制。請參閱[內容模式](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry#choose-a-content-mode)。                                    |

### 傳遞錯誤

當傳遞失敗時，**Delivery** 欄會顯示 **Failing**。將指標停留在其上即可查看錯誤，然後找出可能的原因：

| 錯誤                                                | 可能的原因                                                                                                         |
| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| HTTP error (status 401) 或 HTTP error (status 403) | 驗證標頭錯誤                                                                                                        |
| HTTP error (status 404)                           | **OTLP endpoint URL** 或 **OTLP traces endpoint URL** 中的路徑錯誤                                                   |
| DNS resolution failure                            | 端點的主機名稱無法解析                                                                                                   |
| TLS failure                                       | TLS 問題，例如端點的憑證問題                                                                                              |
| Timeout                                           | 端點未及時回應。請參閱[傳遞逾時](https://platform.claude.com/docs/zh-TW/manage-claude/opentelemetry/api#delivery-and-health) |
| Connection failure                                | API 無法連線至端點                                                                                                   |
