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

本文說明如何將使用 OpenTelemetry 檢測並依賴 Google Cloud 匯出工具的應用程式,改為使用 OpenTelemetry 的 OTLP 匯出工具。這兩種設定都會將遙測資料傳送至您的 Google Cloud 專案。本文件中的步驟適用於 OpenTelemetry SDK 執行的程序內匯出作業。

本文說明如何在使用手動檢測時匯出追蹤記錄資料。這份指南適用於 Java、Go 和 Python,但不適用於將記錄或指標資料傳送至 Google Cloud 專案。

為何要進行遷移

OpenTelemetry SDK 會以 OTLP 格式產生記錄、指標和追蹤資料。當應用程式使用 Google Cloud 匯出工具將資料匯出至Google Cloud 專案時,匯出工具會執行下列步驟:

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

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

手動檢測的遷移指南

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

新增依附元件

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

Java

針對使用 Gradle 建構系統的 Java 應用程式:

// build.gradle
implementation("io.opentelemetry:opentelemetry-exporter-otlp:1.47.0")

Go

針對 Golang 應用程式,請確認 go.mod 檔案具有下列依附元件:

// go.mod file
require(
  // OTLP exporter that uses grpc protocol for export
  go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.34.0
  // Alternatively, for export using http/protobuf protocol, use:
  go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.34.0
)

Python

針對 Python 應用程式,請安裝下列依附元件或更新 requirements.txt 檔案:

# Requirements.txt - use appropriate versions
#
# OTLP exporter that uses grcp protocol for export
opentelemetry-exporter-otlp-proto-grpc==1.30.0
grpcio==1.70.0
# Alternatively, for export using http/protobuf protocol, use:
opentelemetry-exporter-otlp-proto-http==1.30.0

將 Google Cloud 匯出工具的用法替換為 OTLP 匯出工具

更新應用程式程式碼,讓 OpenTelemetry SDK 設定為使用 OpenTelemetry OTLP 匯出器,而非 Google Cloud 追蹤匯出器。必須進行的變更會因語言而異。

Java

import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import io.opentelemetry.sdk.trace.samplers.Sampler;

// Initialize OpenTelemetry SDK with OTLP exporters
public static OpenTelemetry initOpenTelemetry() {
    // Initialize the OTLP gRPC exporter
    SpanExporter otlpGrpcSpanExporter =
        OtlpGrpcSpanExporter.builder()
            .setTimeout(2, TimeUnit.SECONDS)
            .build();

    // Initialize OpenTelemetry tracer provider
    SdkTracerProvider tracerProvider = SdkTracerProvider.builder()
        .setResource(resource)
        .setSampler(Sampler.traceIdRatioBased(0.02))
        .addSpanProcessor(
            BatchSpanProcessor.builder(otlpGrpcSpanExporter)
                .setScheduleDelay(100, TimeUnit.MILLISECONDS)
                .build());

    // Configure OpenTelemetry SDK instacne to use the tracer provider
    // configured with OTLP exporter
    OpenTelemetrySdk openTelemetrySdk =
        OpenTelemetrySdk.builder()
            .setTracerProvider(tracerProvider)
            .build();
}

Go

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

// Initializes OpenTelemetry with OTLP exporters
func init() {
    ctx := context.Background()

    // Initialize the OTLP gRPC exporter
    exporter, err := otlptracegrpc.New(ctx)
    if err != nil {
        panic(err)
    }
    // initialize OpenTelemetry tracer provdier
    tp := sdktrace.NewTracerProvider(
        sdktrace.WithSampler(sdktrace.TraceIDRatioBased(0.02)),
        sdktrace.WithBatcher(exporter)
    )

    // configure OpenTelemetry SDK instance to use the tracer provider
    // configured with OTLP exporter
    otel.SetTracerProvider(tp)
}

Python

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

# Initialize OpenTelemetry with OTLP exporters
def init():
    # Initialize the OTLP gRPC or http exporter
    otlp_grpc_exporter = OTLPSpanExporter()

    # Initialize OpenTelemetry TracerProvider
    trace_provider = TracerProvider(resource=resource).add_span_processor(
    BatchSpanProcessor(otlp_grpc_exporter)
    )

    # Configure OpenTelemetry tracing API with the initialized tracer provider
    trace.set_tracer_provider(trace_provider)

設定驗證機制

在先前對 OpenTelemetry SDK 設定所做的變更後,應用程式會在使用 gRPC 或 HTTP 時,透過 OpenTelemetry OTLP 匯出器匯出追蹤記錄。接下來,您需要設定匯出工具,將這些追蹤記錄傳送至 Google Cloud 專案。

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

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

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

為匯出呼叫設定驗證標頭

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

Java

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

// build.gradle
// Google Auth Library
implementation("com.google.auth:google-auth-library-oauth2-http:1.32.1")

Go

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

// go.mod file
require (
    // When using gRPC based OTLP exporter, auth is built-in
    google.golang.org/grpc v1.70.0
    // When using http based OTLP exported, use explicit auth library
    golang.org/x/oauth2 v0.26.0
)

Python

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

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

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

Java

使用 OpenTelemetry SDK 自動設定模組時,建議您使用 Google Cloud 驗證擴充功能。如需使用此擴充功能的完整範例,請參閱「搭配 Google 驗證的 OTLP 追蹤記錄範例」。

import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import io.opentelemetry.sdk.trace.samplers.Sampler;

import com.google.auth.oauth2.GoogleCredentials;

// Initialize OpenTelemetry SDK with OTLP exporters
public static OpenTelemetry initOpenTelemetry() {
    // Retrieve and store application-default credentials
    GoogleCredentials credentials;
    try {
       credentials = GoogleCredentials.getApplicationDefault();
    } catch (IOException e) {
      // Handle authentication error
      throw new RuntimeException(e);
    }

    // Update gRPC span exporter to add the authorization headers
    // If you are using the Autoconfigure module, we recommend using
    // Google Cloud Authentication Extension.
    // See https://github.com/open-telemetry/opentelemetry-java-contrib/tree/main/gcp-auth-extension
    SpanExporter otlpGrpcSpanExporter =
        OtlpGrpcSpanExporter.builder()
            .setHeaders(
                () -> {
                  Map<String, List<String>> gcpHeaders;
                  try {
                    credentials.refreshIfExpired();
                    gcpHeaders = credentials.getRequestMetadata();
                  } catch (IOException e) {
                    // Handle authentication error
                    throw new RuntimeException(e);
                  }
                  Map<String, String> flattenedHeaders =
                      gcpHeaders.entrySet().stream()
                          .collect(
                              Collectors.toMap(
                                  Map.Entry::getKey,
                                  entry ->
                                      entry.getValue().stream()
                                          .filter(Objects::nonNull)
                                          .filter(s -> !s.isEmpty())
                                          .collect(Collectors.joining(",")),
                                  (v1, v2) -> v2));
                  return flattenedHeaders;
                })
            .setTimeout(2, TimeUnit.SECONDS)
            .build();

  // Other OpenTelemetry configuration remains unaffected
}

Go

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

    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials/oauth"
)

// Initializes OpenTelemetry with OTLP exporters
func init() {
    ctx := context.Background()

    // Retrieve and store Google application-default credentials
    creds, err := oauth.NewApplicationDefault(ctx)
    if err != nil {
        panic(err)
    }

    // Update the previously created OTLP gRPC span exporter to
    // add authorization headers
    exporter, err := otlptracegrpc.New(
        ctx,
        otlptracegrpc.WithDialOption(grpc.WithPerRPCCredentials(creds))
    )

    // Other OpenTelemetry configuration remains unaffected.
}

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

# Initialize OpenTelemetry with OTLP exporters
def init():
    # Retrieve and store Google application-default credentials
    credentials, project_id = google.auth.default()
    # Request used to refresh credentials upon expiry
    request = google.auth.transport.requests.Request()

    # Supply the request and credentials to AuthMetadataPlugin
    # AuthMeatadataPlugin inserts credentials into each request
    auth_metadata_plugin = AuthMetadataPlugin(
        credentials=credentials, request=request
    )

    # Initialize gRPC channel credentials using the AuthMetadataPlugin
    channel_creds = grpc.composite_channel_credentials(
        grpc.ssl_channel_credentials(),
        grpc.metadata_call_credentials(auth_metadata_plugin),
    )

    # Update the previously created OTLP gRPC span exporter to add authorization
    # credentials
    otlp_grpc_exporter = OTLPSpanExporter(credentials=channel_creds)

    # Other OpenTelementry configuration remains unaffected

設定必要的 OpenTelemetry 資源屬性和 OTLP 標頭

設定下列 OpenTelemetry 環境變數:

  • OTEL_RESOURCE_ATTRIBUTES:設定這個環境變數,以便在 OpenTelemetry 資源屬性中設定 gcp.project_id 鍵。請將值設為 Google Cloud 專案的 ID。

範例:

export OTEL_RESOURCE_ATTRIBUTES="gcp.project_id=PROJECT_ID"

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

設定匯出工具端點

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

範例:

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

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

所需權限

有身分與存取權管理 (IAM) 角色和權限,可讓您或服務帳戶將追蹤記錄資料寫入 Telemetry API,並將該資料儲存在 Google Cloud 專案中。舉例來說,如果您只具備 Cloud Trace 角色或權限,則無法使用 Telemetry API 寫入資料。

詳情請參閱「應用程式預設憑證的運作方式」和「為本機開發環境設定應用程式預設憑證 (ADC)」。

必要 API

Telemetry API 預設為停用。您必須啟用這個 API。以下提供有關 API 的資訊,這些 API 可將遙測資料傳送至 Google Cloud 專案,並查看這類資料:

Google Cloud 控制台

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

Enable the APIs

Google Cloud CLI

Enable the Telemetry, Cloud Logging, and Cloud Monitoring, and Cloud Trace APIs:

gcloud services enable telemetry.googleapis.com logging.googleapis.com monitoring.googleapis.com cloudtrace.googleapis.com