使用客户端跟踪记录

本页面介绍了在使用 Cloud Storage 客户端库与 Cloud Storage 互动时,如何通过 OpenTelemetry 启用客户端跟踪记录。您可以使用以下受支持的 Cloud Storage 客户端库收集和查看跟踪记录数据:

概览

通过在 Cloud Storage 客户端库中启用跟踪记录,您可以监控性能、查明延迟问题,并针对 Cloud Storage 请求快速执行调试。跟踪记录可让您查看已完成请求的序列,并详细了解 Cloud Storage 如何接收、管理和响应请求。单个跟踪记录由多个 span组成,这些 span 是应用在整个 Cloud Storage 请求中执行的每个函数或操作的详细记录,并带有时间戳。

优势

收集和传播跟踪记录数据可为您的应用提供以下优势:

  • 增强性能可见性:由于跟踪记录数据是在 Cloud Storage 完成您发出的每个请求时近乎实时生成的,因此您可以快速确定性能瓶颈并检测延迟问题。

  • 错误处理:您可以使用跟踪记录中提供的每个 Cloud Storage 请求的相关信息查明问题出现的位置,从而加快根本原因分析和缩短停机时间。

客户端跟踪记录的工作原理

以下部分详细介绍了跟踪记录收集的工作原理。

如何使用 OpenTelemetry 收集跟踪记录

Cloud Storage 客户端库支持使用 OpenTelemetry SDK 收集跟踪记录数据,以设置收集和传播跟踪记录数据所需的以下组件:

  • 跟踪记录提供程序:Cloud Storage 客户端库使用跟踪记录提供程序来负责创建和管理跟踪系统,包括在应用中生成和管理跟踪记录与 span。

  • 跟踪记录导出器:OpenTelemetry SDK 使用跟踪记录导出器来负责将跟踪记录数据发送到后端可观测性平台(例如 Cloud Trace),您可以在该平台上分析和可视化跟踪记录数据。如需详细了解跟踪记录导出器,请参阅跟踪记录导出器的工作原理

跟踪记录导出器的工作原理

使用 OpenTelemetry SDK 配置跟踪记录包括选择一个可观察性后端,以将数据导出到进行分析、存储和可视化处理的位置。虽然您可以将跟踪记录数据导出到您选择的任何可观测性后端,但我们建议您使用 Cloud Trace,该工具可通过 Google Cloud 控制台访问,并提供与其他 Google Cloud 服务的集成。

配置并启用跟踪记录提供程序和跟踪记录导出器后,您可以近乎实时地查看跟踪记录数据,因为系统会为每个 Cloud Storage 请求生成跟踪记录和 span。

使用Google Cloud 控制台中的 Cloud Trace 探索器,您可以查看包含以下内容的每个跟踪记录:

  • 端到端 Cloud Storage 请求的简要概览。

  • 多个 span(每个 span 都会在已执行的 Cloud Storage 请求中捕获带时间戳的单个操作)。

如需详细了解跟踪记录和 span,请参阅有关跟踪记录和 span 的 OpenTelemetry 文档

价格

跟踪记录数据会产生费用。费用根据 Cloud Trace 提取和扫描的跟踪记录 span 数量进行计算。如需详细了解收费跟踪记录 span 和价格示例,请参阅 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 Agent (roles/coudtrace.agent) IAM 角色。

此预定义角色包含 cloudtrace.traces.patch 权限,而将跟踪记录写入 Cloud Trace 则需要该权限。

您也可以通过预定义角色来获得这些权限,或者可以创建自定义角色来授予特定权限。如需了解如何授予项目的角色,请参阅授予或撤消角色。如需详细了解 Cloud Trace Agent 角色,请参阅 Identity and Access Management (IAM) 文档

为应用配置跟踪

按照以下说明配置跟踪,并开始使用 Cloud Storage 客户端库收集跟踪记录数据:

C++

  1. 安装以下版本:

    • C++ 客户端库 v2.16.0 或更高版本

    • C++ 14 或更高版本

  2. 如需在 C++ 客户端库中启用 OpenTelemetry 跟踪插桩,请更新 CMake 或 Bazel 的构建系统配置

  3. 创建一个 Cloud Storage 客户端实例并启用 OpenTelemetry 跟踪记录。

    #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. 创建一个 Cloud Storage 客户端实例并启用 OpenTelemetry 跟踪记录。

    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 探索器页面中,点击散点图中的特定跟踪记录以查看跟踪记录详情。

    跟踪记录详情窗格会显示跟踪记录 span 的表格。

  3. 可选:点击某个 span 行,以查看有关特定 span 的详细信息,例如以下信息:

    • 属性:用于提供有关该 span 的附加信息的键值对。

    • 日志和事件:与该 span 相关联的日志条目。

    • 堆栈轨迹:与该 span 相关联的堆栈轨迹。

    • 元数据和链接:指向与该 span 关联的其他 Google Cloud 服务的链接。

如需详细了解如何使用 Cloud Trace 探索器,请参阅查找和探索跟踪记录

后续步骤