從追蹤匯出工具遷移至 OTLP 端點

本文說明如何設定 OpenTelemetry SDK,將追蹤資料匯出至 Google Cloud 專案。Java、Go、Python 和 Node.js 的範例說明如何設定 SDK,以便在使用手動檢測時,將追蹤資料傳送至 Telemetry (OTLP) API。這個頁面會針對每種語言,提供如何使用 OTLP 匯出工具,透過支援的匯出通訊協定傳送追蹤資料的相關資訊。

本頁面說明的檢測設備僅適用於追蹤資料。不會將記錄或指標資料傳送至 Google Cloud 專案。

如果應用程式依賴 OpenTelemetry 收集器將追蹤資料傳送至 Google Cloud 專案,則不適用本文:

遷移的優點

OpenTelemetry SDK 會產生記錄、指標和追蹤資料,格式通常與 OpenTelemetry OTLP 通訊協定定義的 proto 檔案一致。不過,欄位可能會先從 OpenTelemetry 專屬資料類型轉換為 JSON 資料類型,再進行儲存。

應用程式使用 Google Cloud 匯出工具將資料匯出至 Google Cloud 專案時,該匯出工具會執行下列步驟:

  1. 將 OTLP 格式的記錄資料轉換為 Cloud Logging API、Cloud Monitoring API 或 Cloud Trace API 定義的專有格式。
  2. 將轉換後的資料傳送至適當的 API,然後儲存在 Google Cloud 專案中。

如果是追蹤資料,建議您將應用程式遷移至使用 Telemetry (OTLP) API 匯出資料,因為這項匯出作業不需要轉換資料。資料轉換可能會導致部分資料遺失。舉例來說,專有格式的特定欄位可能設有較低的限制,或是部分 OTLP 欄位可能無法對應至專有格式的欄位。

可用的樣本

本頁面提及的範例應用程式可在 GitHub 中找到。 大多數應用程式都設定為使用 gRPC 匯出追蹤資料,也就是透過 HTTP/2 連線,使用 gRPC 線路格式的 protobuf 編碼資料。此外,如果應用程式設定為透過 HTTP 連線,以 protobuf 編碼資料的形式匯出追蹤資料,您也可以參考下列範例程式碼:

  • Java 應用程式

    範例應用程式已設定為透過 HTTP 連線,以 protobuf 編碼資料的形式匯出追蹤記錄。 如果您偏好使用 gRPC,則適用於這個範例中的檢測。不過,您需要修改自動設定模組使用的系統屬性。範例應用程式會指定 http/protobuf 匯出工具。如要使用 gRPC,請將這項設定變更為 grpc

    建議您讓 Java 應用程式 (例如範例應用程式) 使用 OpenTelemetry SDK Autoconfigure 模組設定 SDK。

  • 使用 gRPC 的 Go 應用程式使用 HTTP 的 Go 應用程式

    有兩個 Go 存放區。在一個存放區中,範例應用程式會使用 gRPC。另一個存放區中的範例會透過 HTTP 連線使用 protobuf 編碼資料。

  • Python 應用程式

    這個存放區包含兩個範例,一個適用於 gRPC,另一個則透過 HTTP 連線使用 protobuf 編碼資料。

  • Node.js 應用程式

    這個存放區包含兩個範例,一個適用於 gRPC,另一個則透過 HTTP 連線使用 protobuf 編碼資料。

事前準備

將應用程式遷移至 OTLP 端點以傳送追蹤資料前,請先啟用 Telemetry API,並確認您已獲派必要的身分與存取權管理 (IAM) 角色。您可能也需要將 IAM 角色授予服務帳戶。

啟用計費功能和 Telemetry API

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Telemetry, Cloud Logging, Cloud Monitoring, and Cloud Trace APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Telemetry, Cloud Logging, Cloud Monitoring, and Cloud Trace APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  8. 設定權限

    手動檢測機制的遷移指南

    本節說明如何修改應用程式,以便使用 Telemetry API 將追蹤資料傳送至 Google Cloud 專案。您無法將指標或記錄資料傳送至這個端點。

    新增依附元件

    第一步是在應用程式中新增 OpenTelemetry 的 OTLP 追蹤記錄匯出工具的依附元件。選取適合應用程式和建構系統的依附元件版本。

    Java

    如果是 Java 應用程式,請在 build.gradle 指令碼中新增下列依附元件:

    // use the latest versions
    implementation("io.opentelemetry:opentelemetry-exporter-otlp:1.56.0")
    implementation("io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:1.56.0")
    

    Go

    本節說明使用 gRPC 匯出時,您需要對依附元件進行的變更。如果您透過 HTTP 連線匯出 protobuf 編碼資料,請將 otlptracehttp 套件做為依附元件。詳情請參閱「使用 HTTP 的 Go 應用程式」。

    如果是使用 gRPC 匯出的 Go 應用程式,請更新 go.mod 檔案,加入下列依附元件:

    // go.mod file
    require(
      // OTLP exporter that uses grpc protocol for export
      go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0
    )
    

    Python

    本節說明使用 gRPC 匯出時,您需要對依附元件進行的變更。如果透過 HTTP 連線匯出 protobuf 編碼資料,請將 opentelemetry-exporter-otlp-proto-http 套件納入必要條件。詳情請參閱「Python 應用程式」。

    如果是使用 gRPC 匯出的 Python 應用程式,請安裝下列依附元件或更新 requirements.txt 檔案:

    # Requirements.txt - use appropriate versions
    #
    # OTLP exporter that uses grcp protocol for export
    opentelemetry-exporter-otlp-proto-grpc==1.39.0
    grpcio==1.76.0
    

    Node.js

    本節說明使用 gRPC 匯出時,您需要對依附元件進行的變更。如果透過 HTTP 連線匯出 protobuf 編碼資料,請將 @opentelemetry/exporter-trace-otlp-proto 封裝做為依附元件。詳情請參閱「Node.js 應用程式」。

    如果是使用 gRPC 匯出的 Node.js 應用程式,請新增下列依附元件。

    "@opentelemetry/exporter-trace-otlp-grpc": "0.203.0",
    "@grpc/grpc-js": "1.13.4",
    

    將 Google Cloud 匯出工具替換為 OTLP 匯出工具

    更新應用程式程式碼,將 OpenTelemetry SDK 設為使用 OpenTelemetry OTLP 匯出器,而非 Google Cloud 追蹤記錄匯出器。所需變更因語言而異。

    Java

    如果是 Java 應用程式,請按照下列步驟操作:

    1. 新增下列匯入陳述式:

      import io.opentelemetry.sdk.OpenTelemetrySdk;
      import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
      
    2. 更新應用程式程式碼,使用 OpenTelemetry SDK Autoconfigure 模組設定 SDK:

      public static void main(String[] args) {
          // Configure the OpenTelemetry pipeline with Auto configuration
          openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk();
          ...
      }
      
    3. 設定自動設定模組在執行階段使用的系統屬性。該模組會使用這些屬性啟動 SDK。您也可以使用環境變數,取代系統屬性。詳情請參閱「環境變數和系統屬性」。

      範例應用程式會在 build.gradle 指令碼中定義系統屬性:

      // You can switch the desired protocol here by changing `otel.exporter.otlp.protocol`.
      def autoconf_config = [
        '-Dotel.exporter.otlp.endpoint=https://telemetry.googleapis.com',
        '-Dotel.traces.exporter=otlp',
        '-Dotel.logs.exporter=none',
        '-Dotel.metrics.exporter=none',
        '-Dotel.service.name=my-service',
        '-Dotel.exporter.otlp.protocol=http/protobuf',
        '-Dotel.java.global-autoconfigure.enabled=true',
        // ID of your Google Cloud Project, required by the auth extension
        '-Dgoogle.cloud.project=PROJECT_ID',
      ]
      
      // Now pass the config as JVM arguments to your java application:
      application {
              // Replace with the fully qualified name of your Main class.
        mainClassName = 'com.example.Main'
        applicationDefaultJvmArgs = autoconf_config
      }
      

      如果您偏好使用 gRPC 匯出追蹤記錄資料,請將 OTLP 協定設為 grpc,而非 http/protobuf

    Go

    本節說明使用 gRPC 匯出時需要進行的變更。如果透過 HTTP 連線匯出 protobuf 編碼資料,則必須匯入 otlptracehttp 套件,並使用對應選項設定匯出工具。詳情請參閱「使用 HTTP 的 Go 應用程式」。

    如果是使用 gRPC 匯出的 Go 應用程式,請新增下列 import 陳述式:

    import (
        "context"
        "go.opentelemetry.io/otel"
        "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
        sdktrace "go.opentelemetry.io/otel/sdk/trace"
        // other dependencies
    )
    

    此外,請更新初始化程式碼,使用 gRPC 匯出工具設定 TraceProvider

    
    // Initializes OpenTelemetry with OTLP exporters
    ctx := context.Background()
    
    // creds: configure Application Default Credentials
    
    // Initialize the OTLP gRPC exporter
    exporter, err := otlptracegrpc.New(ctx)
    if err != nil {
      panic(err)
    }
    
    // set OTEL_RESOURCE_ATTRIBUTES="gcp.project_id=<project_id>"
    // set endpoint with OTEL_EXPORTER_OTLP_ENDPOINT=https://<endpoint>
    // set OTEL_EXPORTER_OTLP_HEADERS="x-goog-user-project=<project_id>"
    exporter, err := otlptracegrpc.New(ctx, otlptracegrpc.WithDialOption(grpc.WithPerRPCCredentials(creds)))
    if err != nil {
      panic(err)
    }
    
    tp := sdktrace.NewTracerProvider(
      // For this example code we use sdktrace.AlwaysSample sampler to sample all traces.
      // In a production application, use sdktrace.TraceIDRatioBased with a desired probability.
      sdktrace.WithSampler(sdktrace.AlwaysSample()),
      sdktrace.WithBatcher(exporter))
    
    otel.SetTracerProvider(tp)
    

    Python

    本節說明使用 gRPC 匯出時需要進行的變更。如果透過 HTTP 連線匯出以 protobuf 編碼的資料,則必須從 opentelemetry.exporter.otlp.proto.http 套件匯入,並使用對應選項設定匯出工具。詳情請參閱「Python 應用程式」。

    如果是使用 gRPC 匯出的 Python 應用程式,請新增下列匯入項目:

    from opentelemetry import trace
    from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
        OTLPSpanExporter,
    )
    from opentelemetry.sdk.resources import SERVICE_NAME, Resource
    

    此外,請更新初始化程式碼,使用 gRPC 匯出工具設定 TraceProvider

    # Initialize OpenTelemetry with OTLP exporters
    
    # channel_creds: configure Application Default Credentials
    
    trace_provider = TracerProvider(resource=resource)
    processor = BatchSpanProcessor(
        OTLPSpanExporter(
            credentials=channel_creds,
            endpoint="https://telemetry.googleapis.com:443/v1/traces",
        )
    )
    trace_provider.add_span_processor(processor)
    trace.set_tracer_provider(trace_provider)
    tracer = trace.get_tracer("my.tracer.name")
    

    Node.js

    本節說明使用 gRPC 匯出時需要進行的變更。如果透過 HTTP 連線匯出 protobuf 編碼資料,請匯入 @opentelemetry/exporter-trace-otlp-proto 套件。詳情請參閱「Node.js 應用程式」。

    如要使用 gRPC 匯出 Node.js 應用程式,請新增下列匯入項目:

    import {OTLPTraceExporter} from '@opentelemetry/exporter-trace-otlp-grpc';
    

    此外,請更新初始化程式碼,使用 gRPC 匯出工具設定 TraceProvider

    
    // Express App that exports traces via gRPC with protobuf
    async function main() {
      // authenticatedClient: configure Application Default Credentials
    
      // Configure the TraceExporter
      const sdk = new NodeSDK({
        traceExporter: new OTLPTraceExporter({
          credentials: credentials.combineChannelCredentials(
            credentials.createSsl(),
            credentials.createFromGoogleCredential(authenticatedClient),
          ),
        }),
      });
      sdk.start();
    }
    

    設定驗證機制

    完成先前對 OpenTelemetry SDK 設定的變更後,應用程式就會設定為使用 OpenTelemetry OTLP 匯出工具,透過 gRPC 或 HTTP 匯出追蹤記錄。接著,您需要設定匯出工具,將這些追蹤記錄傳送至您的 Google Cloud 專案。

    如要設定驗證,請按照下列步驟操作:

    1. 為匯出呼叫設定驗證標頭
    2. 設定必要的 OpenTelemetry 資源屬性和 OTLP 標頭
    3. 設定匯出工具端點

    本節將詳細說明每個步驟。

    為匯出呼叫設定驗證標頭

    如要使用 Google Cloud 應用程式預設憑證 (ADC) 設定匯出工具,請新增特定語言的 Google Auth 程式庫。

    Java

    如要向 Google Cloud Observability 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    如果Java 應用程式使用 OpenTelemetry SDK Autoconfigure 模組,建議您也使用 Google Cloud Authentication Extension

    // build.gradle
    implementation("io.opentelemetry.contrib:opentelemetry-gcp-auth-extension:1.52.0-alpha")
    

    Go

    如要向 Google Cloud Observability 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    如果是使用 gRPC 匯出的 Go 應用程式,請更新 go.mod 檔案,加入下列依附元件:

    // go.mod file
    require (
        // When using gRPC based OTLP exporter, auth is built-in
        google.golang.org/grpc v1.75.1
    )
    

    如果是使用 HTTP 匯出的 Go 應用程式,請更新 go.mod 檔案,加入下列依附元件:

    // go.mod file
    require (
        // When using http based OTLP exported, use explicit auth library
      golang.org/x/oauth2 v0.31.0
    )
    

    Python

    如要向 Google Cloud Observability 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    如果是 Python 應用程式,請新增下列匯入項目:

    # requirements.txt
    # Google Auth Library
    google-auth==2.38.0
    

    Node.js

    如要向 Google Cloud Observability 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

    如果是 Node.js 應用程式,請新增下列依附元件:

    "google-auth-library": "9.15.1",
    

    接著,請更新建構 OTLP span 匯出器的應用程式碼,將從程式庫擷取的授權權杖新增至標頭。這個步驟會因語言而異,但所有語言的實作方式都類似。

    Java

    如果您有使用 OpenTelemetry SDK Autoconfigure 模組Google Cloud Authentication ExtensionJava 應用程式,則在應用程式初始化期間,不需要執行任何特殊步驟。自動設定模組會自動執行設定 ADC 的必要步驟。

    Go

    本節說明使用 gRPC 匯出時需要進行的變更。如果透過 HTTP 連線匯出 protobuf 編碼資料,則必須匯入 otlptracehttp 套件,並將匯出工具設定為 otlptracehttp 物件。詳情請參閱「使用 HTTP 的 Go 應用程式」。

    如果是使用 gRPC 匯出的 Go 應用程式,請新增下列匯入陳述式:

    import (
        "context"
        "go.opentelemetry.io/otel"
        "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
        sdktrace "go.opentelemetry.io/otel/sdk/trace"
        // other dependencies
        "google.golang.org/grpc"
        "google.golang.org/grpc/credentials/oauth"
    )
    

    此外,請更新初始化程式碼,在例項化 gRPC 匯出工具之前設定 ADC:

    // Initializes OpenTelemetry with OTLP exporters
    ctx := context.Background()
    
    // Retrieve and store Google application-default credentials
    creds, err := oauth.NewApplicationDefault(ctx)
    if err != nil {
      panic(err)
    }
    
    // set OTEL_RESOURCE_ATTRIBUTES="gcp.project_id=<project_id>"
    // set endpoint with OTEL_EXPORTER_OTLP_ENDPOINT=https://<endpoint>
    // set OTEL_EXPORTER_OTLP_HEADERS="x-goog-user-project=<project_id>"
    exporter, err := otlptracegrpc.New(ctx, otlptracegrpc.WithDialOption(grpc.WithPerRPCCredentials(creds)))
    if err != nil {
      panic(err)
    }
    
    // Other OpenTelemetry configuration remains unaffected.
    

    Python

    本節說明使用 gRPC 匯出時需要進行的變更。如果透過 HTTP 連線匯出 protobuf 編碼資料,請使用預設憑證。例項化 BatchSpanProcessor 時,也必須傳遞這些憑證。詳情請參閱「Python 應用程式」。

    如果是使用 gRPC 匯出的 Python 應用程式,請新增下列匯入項目:

    from opentelemetry import trace
    from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
        OTLPSpanExporter,
    )
    from opentelemetry.sdk.resources import SERVICE_NAME, Resource
    
    import google.auth
    import google.auth.transport.grpc
    import google.auth.transport.requests
    import grpc
    from google.auth.transport.grpc import AuthMetadataPlugin
    

    此外,請更新初始化程式碼,在例項化 gRPC 匯出工具之前設定 ADC:

    credentials, _ = google.auth.default()
    request = google.auth.transport.requests.Request()
    resource = Resource.create(attributes={SERVICE_NAME: "otlp-gcp-grpc-sample"})
    
    auth_metadata_plugin = AuthMetadataPlugin(credentials=credentials, request=request)
    channel_creds = grpc.composite_channel_credentials(
        grpc.ssl_channel_credentials(),
        grpc.metadata_call_credentials(auth_metadata_plugin),
    )
    
    # Configure the TraceProvider
    

    Node.js

    本節說明使用 gRPC 匯出時需要進行的變更。如果您透過 HTTP 連線匯出 protobuf 編碼資料,則需要進行的變更與本文所述略有不同。詳情請參閱 Node.js 應用程式中包含的 app-http-proto-export.ts 檔案。

    如要使用 gRPC 匯出 Node.js 應用程式,請新增下列匯入項目:

    import {AuthClient, GoogleAuth} from 'google-auth-library';
    import {credentials} from '@grpc/grpc-js';
    

    此外,請更新初始化程式碼,在例項化 gRPC 匯出工具之前設定 ADC:

    async function getAuthenticatedClient(): Promise<AuthClient> {
      const auth: GoogleAuth = new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/cloud-platform',
      });
      return await auth.getClient();
    }
    
    // Express App that exports traces via gRPC with protobuf
    async function main() {
      const authenticatedClient: AuthClient = await getAuthenticatedClient();
    
      // Configure the TraceExporter
    }
    

    設定必要的 OpenTelemetry 資源屬性

    OTEL_RESOURCE_ATTRIBUTES 環境變數中,新增指定專案的鍵值配對。如需金鑰,請使用 gcp.project_id。 請使用 Google Cloud 專案的 ID 做為值。

    範例:

    export OTEL_RESOURCE_ATTRIBUTES="gcp.project_id=PROJECT_ID"
    

    如果您使用 Java 並設定應用程式,以使用 Google Cloud Authentication Extension (如範例 Java 應用程式),則不需要將專案 ID 設為 OpenTelemetry 資源屬性的一部分。不過,設定這項屬性不會造成任何損害。

    如要進一步瞭解 OpenTelemetry 環境變數,請參閱「一般 SDK 設定」。

    設定配額專案 ID

    配額專案是 Google Cloud 專案,可追蹤 API 要求的使用情形。由於 Telemetry API 是以用戶端為基礎的 API,因此驗證方式會決定系統是否自動識別配額專案。舉例來說,使用服務帳戶進行驗證時,您不需要指定配額專案。不過,使用使用者憑證進行驗證時,您需要指定配額專案。

    您可以使用環境變數設定配額專案。如要判斷要為程式設計語言設定哪個環境變數,請參閱「使用環境變數設定配額專案」。

    舉例來說,如果是 Go,您可以按照下列方式設定配額專案:

    export GOOGLE_CLOUD_QUOTA_PROJECT="QUOTA_PROJECT_ID"
    

    如要瞭解如何解決驗證錯誤,請參閱「使用者憑證無法運作」。

    設定匯出工具端點

    OTEL_EXPORTER_OTLP_ENDPOINT 環境變數的值設為 Google Cloud的 OTLP 端點。

    範例:

    export OTEL_EXPORTER_OTLP_ENDPOINT=https://telemetry.googleapis.com
    

    如果您使用 Java 和自動設定模組,可以像範例 Java 應用程式一樣,使用系統屬性設定匯出工具端點。您不需要為該設定設定匯出工具環境變數。

    如要進一步瞭解 OpenTelemetry 環境變數,請參閱「一般 SDK 設定」。