从 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 导出器

    更新您的应用代码,以便 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 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 span 导出器的应用代码,以便将从库中检索到的授权令牌添加到标头中。此步骤因语言而异,但所有语言的实现方式都是类似的。

    Java

    我们建议您在使用 OpenTelemetry SDK 自动配置模块时使用 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 配置