使用用戶端追蹤

本頁說明如何使用 Cloud Storage 用戶端程式庫與 Cloud Storage 互動時,透過 OpenTelemetry 啟用用戶端追蹤。您可以使用下列支援的 Cloud Storage 用戶端程式庫,收集及查看追蹤記錄資料:

總覽

在 Cloud Storage 用戶端程式庫中啟用追蹤功能,即可監控效能、找出延遲問題,並快速對 Cloud Storage 要求執行偵錯。追蹤記錄可顯示已完成要求的順序,詳細說明 Cloud Storage 如何接收、管理及回應要求。單一追蹤記錄是由多個範圍組成,這些範圍是詳細的記錄,包含應用程式在整個 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 角色。

這個預先定義的角色具備 cloudtrace.traces.patch 權限,可將追蹤記錄寫入 Cloud Trace。

您或許還可透過預先定義的角色取得這些權限,或建立自訂角色來授予特定權限。如需授予專案角色的操作說明,請參閱授予或撤銷角色。如要進一步瞭解 Cloud Trace Agent 角色,請參閱 Identity and Access Management (IAM) 說明文件

設定應用程式的追蹤功能

請按照下列操作說明設定追蹤功能,並使用 Cloud Storage 用戶端程式庫開始收集追蹤資料:

C++

  1. 安裝下列版本:

    • C++ 用戶端程式庫 2.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. 設定追蹤匯出工具和追蹤提供者。 <0x0A

    
    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 Explorer」頁面:

    前往「Trace Explorer」頁面

    您也可以透過搜尋列找到這個頁面。

  2. 在「Trace explorer」(追蹤探索工具) 頁面中,按一下散佈圖中的特定追蹤記錄,即可查看追蹤記錄詳細資料。

    「Trace details」(追蹤記錄詳細資料) 窗格會顯示追蹤記錄時距表格。

  3. 選用:按一下跨度資料列,即可查看特定跨度的詳細資訊,例如:

    • 屬性:提供有關範圍的其他資訊的鍵/值組合。

    • 記錄和事件:與時間間隔相關聯的記錄項目。

    • 堆疊追蹤:與範圍相關聯的堆疊追蹤。

    • 中繼資料和連結:與時間間隔相關聯的其他 Google Cloud 服務連結。

如要進一步瞭解如何使用 Cloud Trace 探索工具,請參閱「尋找及探索追蹤記錄」。

後續步驟