Trace エクスポータから 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 プロジェクトに保存します。

トレースデータの場合は、データ変換を必要としない Telemetry(OTLP)API を使用してデータをエクスポートするようにアプリケーションを移行することをおすすめします。データ変換により、一部のデータが失われる可能性があります。たとえば、独自形式では特定のフィールドの制限が低い場合や、一部の OTLP フィールドが独自形式のフィールドにマッピングされない場合があります。

始める前に

トレースデータを OTLP エンドポイントに送信するようにアプリケーションを移行する前に、Telemetry API を有効にして、必要な Identity and Access Management(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.

    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.

    Enable the APIs

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

    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.

    Enable the APIs

  8. 権限を構成する

    手動計測の移行ガイド

    このセクションでは、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 エクスポータに置き換える

    アプリケーション コードを更新して、 Google Cloud トレース エクスポータではなく OpenTelemetry OTLP エクスポータを使用するように OpenTelemetry SDK を構成します。必要な変更は言語によって異なります。

    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 Auth ライブラリを追加します。

    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 Autoconfigure モジュールを使用する場合は、Google Cloud 認証拡張機能を使用することをおすすめします。この拡張機能を使用する詳細な例については、Google Auth を使用した 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 リソース属性を構成する

    プロジェクトを指定するキーと値のペアを OTEL_RESOURCE_ATTRIBUTES 環境変数に追加します。キーには gcp.project_id を使用します。値には、 Google Cloud プロジェクトの ID を使用します。

    例:

    export OTEL_RESOURCE_ATTRIBUTES="gcp.project_id=PROJECT_ID"
    

    OpenTelemetry 環境変数の詳細については、一般的な SDK 構成をご覧ください。

    割り当てプロジェクト ID を設定する

    割り当てプロジェクトは、API リクエストの使用状況を追跡する Google Cloud プロジェクトです。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
    

    OpenTelemetry 環境変数の詳細については、一般的な SDK 構成をご覧ください。