クライアントサイドのトレースを使用する

このページでは、Cloud Storage クライアント ライブラリを使用して Cloud Storage とやり取りするときに、OpenTelemetry でクライアントサイドのトレースを有効にする方法について説明します。トレースデータを収集して表示するには、サポートされている次の Cloud Storage クライアント ライブラリを使用します。

概要

Cloud Storage クライアント ライブラリでトレースを有効にすると、パフォーマンスをモニタリングし、レイテンシの問題を特定して、Cloud Storage リクエストのデバッグをすばやく実行できます。トレースを使用すると、完了したリクエストのシーケンスを確認できます。これにより、リクエストが Cloud Storage によってどのように受信、管理、応答されたのかを把握できます。1 つのトレースは複数のスパンで構成されます。スパンは、Cloud Storage リクエスト全体でアプリケーションが実行した各関数またはオペレーションの詳細を含むタイムスタンプ付きレコードです。

利点

トレースデータの収集と伝播は、アプリケーションに対して次の利点があります。

  • パフォーマンスの可視性の向上: トレースデータは、Cloud Storage が各リクエストを完了するときにほぼリアルタイムで生成されるため、パフォーマンスのボトルネックをすばやく特定し、レイテンシの問題を検出できます。

  • エラー処理: トレースで提供される Cloud Storage リクエストに関する情報により、問題が発生した場所を特定し、根本原因の分析を迅速に行い、ダウンタイムを短縮できます。

クライアントサイド トレースの仕組み

以降のセクションでは、トレース収集の仕組みについて詳しく説明します。

OpenTelemetry でのトレース収集の仕組み

Cloud Storage クライアント ライブラリは、OpenTelemetry SDK を使用してトレースデータの収集をサポートし、トレースデータの収集と伝播に必要な次のコンポーネントを設定します。

  • トレース プロバイダ: Cloud Storage クライアント ライブラリで使用されるトレース プロバイダは、アプリケーション内のトレースやスパンの生成と管理など、トレース システムの作成と管理を行います。

  • トレース エクスポーター: OpenTelemetry SDK で使用されるトレース エクスポーターは、トレースデータを Cloud Trace などのバックエンド オブザーバビリティ プラットフォームに送信し、トレースデータの分析と可視化ができるようにします。トレース エクスポーターの詳細については、トレース エクスポーターの仕組みをご覧ください。

トレース エクスポーターの仕組み

OpenTelemetry SDK を使用してトレースを構成するには、分析、保存、可視化を行う場所にデータをエクスポートするオブザーバビリティ バックエンドを選択します。トレースデータを任意のオブザーバビリティ バックエンドにエクスポートできますが、Cloud Trace を使用することをおすすめします。これは、 Google Cloud コンソールからアクセスでき、他の Google Cloud サービスと統合できます。

トレース プロバイダとトレース エクスポーターを構成して有効にすると、各 Cloud Storage リクエストに対してトレースとスパンが生成されるため、トレースデータを準リアルタイムで表示できます。

Google Cloud コンソールの Cloud Trace エクスプローラを使用すると、次のものを含むトレースを表示できます。

  • Cloud Storage リクエストのエンドツーエンドの概要。

  • 複数のスパン。各スパンは、Cloud Storage リクエスト内で実行された単一オペレーションをタイムスタンプ付きでキャプチャします。

トレースとスパンの詳細については、OpenTelemetry ドキュメントでトレースとスパンの説明をご覧ください。

料金

トレースデータは有料です。Cloud Trace によって取り込まれ、スキャンされたトレーススパンの数に基づいて課金されます。課金対象のトレーススパンと料金の例の詳細については、Cloud Trace の費用をご覧ください。

始める前に

Cloud Storage API の使用状況のトレースを収集する前に、次の手順を完了する必要があります。

  1. Cloud Storage クライアント ライブラリをインストールします

  2. 認証を設定します

  3. Enable the Cloud Trace API.

    Enable the API

  4. Cloud Storage API を有効にします。

    API を有効にする

必要なロール

Cloud Trace にトレースを書き込むために必要な権限を取得するには、クライアントが使用するプロジェクトに対する Cloud Trace エージェントroles/coudtrace.agent)IAM ロールを付与するよう管理者に依頼してください。

この事前定義ロールには、Cloud Trace にトレースを書き込むために必要な cloudtrace.traces.patch 権限が含まれています。

事前定義ロールを使用してこれらの権限を取得することもできます。また、カスタムロールを作成して特定の権限を付与することもできます。プロジェクトにロールを付与する手順については、ロールの付与または取り消しをご覧ください。Cloud Trace エージェントのロールの詳細については、Identity and Access Management(IAM)のドキュメントをご覧ください。

アプリケーションのトレースを構成する

次の手順でトレースを構成し、Cloud Storage クライアント ライブラリを使用してトレースデータの収集を開始します。

C++

  1. 次のバージョンをインストールします。

    • C++ クライアント ライブラリ バージョン v2.16.0 以降

    • C++ バージョン 14 以降

  2. C++ クライアント ライブラリで OpenTelemetry トレース計測を有効にするには、CMake または Bazel のビルドシステム構成を更新します。

  3. OpenTelemetry トレースを有効にして Cloud Storage クライアントのインスタンスを作成します。

    #include "google/cloud/opentelemetry/configure_basic_tracing.h"
    #include "google/cloud/storage/client.h"
    #include "google/cloud/opentelemetry_options.h"
    #include <iostream>
    
    int main(int argc, char* argv[]) {
      if (argc != 3) {
        std::cerr << "Usage: " << argv[0] << " <bucket-name> <project-id>\n";
        return 1;
      }
      std::string const bucket_name = argv[1];
      std::string const project_id = argv[2];
    
      // Create aliases to make the code easier to read.
      namespace gc = ::google::cloud;
      namespace gcs = ::google::cloud::storage;
    
      // Instantiate a basic tracing configuration which exports traces to Cloud
      // Trace. By default, spans are sent in batches and always sampled.
      auto project = gc::Project(project_id);
      auto configuration = gc::otel::ConfigureBasicTracing(project);
    
      // Create a client with OpenTelemetry tracing enabled.
      auto options = gc::Options{}.set<gc::OpenTelemetryTracingOption>(true);
      auto client = gcs::Client(options);
    
      auto writer = client.WriteObject(bucket_name, "quickstart.txt");
      writer << "Hello World!";
      writer.Close();
      if (!writer.metadata()) {
        std::cerr << "Error creating object: " << writer.metadata().status()
                  << "\n";
        return 1;
      }
      std::cout << "Successfully created object: " << *writer.metadata() << "\n";
    
      auto reader = client.ReadObject(bucket_name, "quickstart.txt");
      if (!reader) {
        std::cerr << "Error reading object: " << reader.status() << "\n";
        return 1;
      }
    
      std::string contents{std::istreambuf_iterator<char>{reader}, {}};
      std::cout << contents << "\n";
    
      // The basic tracing configuration object goes out of scope. The collected
      // spans are flushed to Cloud Trace.
    
      return 0;
    }

Java

  1. 次の Cloud Storage Java クライアント ライブラリ バージョンをインストールします。

    • com.google.cloud:google-cloud-storage:2.47.0 以降

    • com.google.cloud:libraries-bom:26.53.0 以降

  2. OpenTelemetry 用 Cloud Trace エクスポーターをインストールします。任意のエクスポーターを使用することもできます。

  3. Cloud Trace プロパゲーターをインストールします。

  4. OpenTelemetry トレースを有効にして Cloud Storage クライアントのインスタンスを作成します。

    public class QuickstartOpenTelemetrySample {
      public static void main(String... args) throws Exception {
        SpanExporter spanExporter = TraceExporter.createWithDefaultConfiguration();
        TextMapPropagator propagators =
            TextMapPropagator.composite(
                W3CTraceContextPropagator.getInstance(),
                new XCloudTraceContextPropagator(/* oneway= */ true));
    
        OpenTelemetrySdk openTelemetry =
            OpenTelemetrySdk.builder()
                .setPropagators(ContextPropagators.create(propagators))
                .setTracerProvider(
                    SdkTracerProvider.builder()
                        // Sample Rate is set to alwaysOn
                        // It is recommended to sample based on a ratio for standard use ie.
                        // .setSampler(Sampler.traceIdRatioBased(0.2)) // sample only 20% of trace ids
                        .setSampler(Sampler.alwaysOn())
                        .addSpanProcessor(BatchSpanProcessor.builder(spanExporter).build())
                        .build())
                .build();
        StorageOptions options = StorageOptions.newBuilder().setOpenTelemetry(openTelemetry).build();
        Storage storage = options.getService();
        System.out.println("Created an instance of storage with OpenTelemetry configured");
      }
    }

Python

  1. Cloud Storage Python クライアント ライブラリをインストールします。

    pip install google-cloud-storage[tracing]>=2.18.0
  2. Cloud Trace エクスポーターとプロパゲータをインストールします。任意のエクスポーターを使用することもできます。

    pip install opentelemetry-exporter-gcp-trace opentelemetry-propagator-gcp
  3. OpenTelemetry リクエスト計測をインストールして、基盤となる HTTP リクエストをトレースします。

    pip install opentelemetry-instrumentation-requests
  4. Python ストレージ クライアントのトレースを個別に有効にするように環境変数を設定します。

    export ENABLE_GCS_PYTHON_CLIENT_OTEL_TRACES=True
  5. トレース エクスポーターとトレース プロバイダを構成します。

    
    from opentelemetry import trace
    from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
    from opentelemetry.resourcedetector.gcp_resource_detector import (
        GoogleCloudResourceDetector,
    )
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import BatchSpanProcessor
    from opentelemetry.sdk.trace.sampling import ALWAYS_ON
    # Optional: Enable traces emitted from the requests HTTP library.
    from opentelemetry.instrumentation.requests import RequestsInstrumentor
    
    from google.cloud import storage
    
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The ID of your GCS object
    # blob_name = "your-object-name"
    # The contents to upload to the file
    # data = "The quick brown fox jumps over the lazy dog."
    
    # In this sample, we use Google Cloud Trace to export the OpenTelemetry
    # traces: https://cloud.google.com/trace/docs/setup/python-ot
    # Choose and configure the exporter for your environment.
    
    tracer_provider = TracerProvider(
        # Sampling is set to ALWAYS_ON.
        # It is recommended to sample based on a ratio to control trace ingestion volume,
        # for instance, sampler=TraceIdRatioBased(0.2)
        sampler=ALWAYS_ON,
        resource=GoogleCloudResourceDetector().detect(),
    )
    
    # Export to Google Cloud Trace.
    tracer_provider.add_span_processor(BatchSpanProcessor(CloudTraceSpanExporter()))
    trace.set_tracer_provider(tracer_provider)
    
    # Optional: Enable traces emitted from the requests HTTP library.
    RequestsInstrumentor().instrument(tracer_provider=tracer_provider)
    
    # Get the tracer and create a new root span.
    tracer = tracer_provider.get_tracer("My App")
    with tracer.start_as_current_span("trace-quickstart"):
        # Instantiate a storage client and perform a write and read workload.
        storage_client = storage.Client()
        bucket = storage_client.bucket(bucket_name)
        blob = bucket.blob(blob_name)
        blob.upload_from_string(data)
        print(f"{blob_name} uploaded to {bucket_name}.")
    
        blob.download_as_bytes()
        print("Downloaded storage object {} from bucket {}.".format(blob_name, bucket_name))
    

トレースを表示する

Cloud Trace エクスプローラを使用して、 Google Cloud コンソールでトレースデータを表示します。

  1. Google Cloud コンソールで、[Trace エクスプローラ] ページに移動します。

    [Trace エクスプローラ] に移動

    このページは、検索バーを使用して見つけることもできます。

  2. [Trace エクスプローラ] ページの散布図で特定のトレースをタップして、トレースの詳細を表示します。

    [トレースの詳細] ペインには、トレーススパンの表が表示されます。

  3. 省略可: スパンの行をクリックすると、特定のスパンに関する次のような詳細情報が表示されます。

    • 属性: スパンに関する追加情報を提供する Key-Value ペア。

    • ログとイベント: スパンに関連付けられているログエントリ。

    • スタック トレース: スパンに関連付けられているスタック トレース。

    • メタデータとリンク: スパンに関連付けられている他のサービスへのリンク。 Google Cloud

Cloud Trace エクスプローラの使用方法について詳しくは、トレースを検索して調査するをご覧ください。

次のステップ