Go 和 OpenTelemetry

此页面适用于希望使用 OpenTelemetry 收集 Go 应用的 Cloud Trace 数据的开发者。OpenTelemetry 是一个供应商中立的插桩框架,可用于收集跟踪记录和指标数据。如需了解如何对代码进行插桩,请参阅插桩和可观测性

  • 安装 OpenTelemetry 软件包。
  • 配置应用以将 span 导出到 Cloud Trace。
  • 配置您的平台。

如需了解版本信息,请参阅以下内容:

如需了解 OpenTelemetry 参考内容,请参阅以下内容:

有关适用于 Go 的 OpenTelemetry 的最新详细信息以及其他文档和示例,请参阅 OpenTelemetry

准备工作

  1. 在 Google Cloud 控制台的导航面板中,选择 API 和服务,点击启用 API 和服务,然后启用 Cloud Trace API:

    转到 Cloud Trace API 设置

  2. 如果系统显示 API 已启用,则表示此 API 已经启用。如未显示,请点击启用按钮。

安装、初始化和使用客户端

请参阅以下说明,了解如何在 Compute Engine 和 Google Kubernetes Engine 上对 Go 应用进行插桩处理。 有关使用 OpenTelemetry 的一般示例,请参阅适用于 Go 的 OpenTelemetry GitHub 代码库

Compute Engine

安装 OpenTelemetry 软件包:

go get go.opentelemetry.io/otel
go get github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace

导入 OpenTelemetry 和 Cloud Trace 导出软件包:

import (
	"context"
	"errors"
	"log"
	"os"

	texporter "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace"
	"go.opentelemetry.io/contrib/detectors/gcp"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
)

创建导出器和跟踪记录提供程序:

func main() {
	// Create exporter.
	ctx := context.Background()
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	exporter, err := texporter.New(texporter.WithProjectID(projectID))
	if err != nil {
		log.Fatalf("texporter.New: %v", err)
	}

	// Identify your application using resource detection
	res, err := resource.New(ctx,
		// Use the GCP resource detector to detect information about the GCP platform
		resource.WithDetectors(gcp.NewDetector()),
		// Keep the default detectors
		resource.WithTelemetrySDK(),
		// Add your own custom attributes to identify your application
		resource.WithAttributes(
			semconv.ServiceNameKey.String("my-application"),
		),
	)
	if errors.Is(err, resource.ErrPartialResource) || errors.Is(err, resource.ErrSchemaURLConflict) {
		log.Println(err)
	} else if err != nil {
		log.Fatalf("resource.New: %v", err)
	}

	// Create trace provider with the exporter.
	//
	// By default it uses AlwaysSample() which samples all traces.
	// In a production environment or high QPS setup please use
	// probabilistic sampling.
	// Example:
	//   tp := sdktrace.NewTracerProvider(sdktrace.WithSampler(sdktrace.TraceIDRatioBased(0.0001)), ...)
	tp := sdktrace.NewTracerProvider(
		sdktrace.WithBatcher(exporter),
		sdktrace.WithResource(res),
	)
	defer tp.Shutdown(ctx) // flushes any pending spans, and closes connections.
	otel.SetTracerProvider(tp)

	// Create custom span.
	tracer := otel.GetTracerProvider().Tracer("example.com/trace")
	err = func(ctx context.Context) error {
		ctx, span := tracer.Start(ctx, "foo")
		defer span.End()

		// Do some work.

		return nil
	}(ctx)
}

创建导出器时,您需要提供 Google Cloud 项目标识符的相关信息。在本示例中,标识符存储在环境变量 GOOGLE_CLOUD_PROJECT 中。

示例应用调用 WithBatcher 函数来配置跟踪记录提供程序,以使用后台进程将 span 发送到 Cloud Monitoring。此示例还配置为在应用退出时调用导出器的 Shutdown 函数。当 Shutdown 执行时,它会将所有待处理 span 发送到 Cloud Monitoring。示例中显示的配置是所有操作环境的推荐实现,包括可随时关停容器的 Cloud Run。

创建 Tracer 实例时,您需要为其提供一个名称。在示例中,名称为 example.com/trace。由于此策略使您可拥有多个实例,我们建议您按照所跟踪的组件来命名这些实例。

执行示例时,系统会创建一个名为 foo 的跟踪记录。

GKE

将以下内容添加到 Dockerfile 中:

RUN go get go.opentelemetry.io/otel
RUN go get github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace

导入 OpenTelemetry 和 Cloud Trace 导出软件包:

import (
	"context"
	"errors"
	"log"
	"os"

	texporter "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace"
	"go.opentelemetry.io/contrib/detectors/gcp"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
)

创建导出器和跟踪记录提供程序:

func main() {
	// Create exporter.
	ctx := context.Background()
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	exporter, err := texporter.New(texporter.WithProjectID(projectID))
	if err != nil {
		log.Fatalf("texporter.New: %v", err)
	}

	// Identify your application using resource detection
	res, err := resource.New(ctx,
		// Use the GCP resource detector to detect information about the GCP platform
		resource.WithDetectors(gcp.NewDetector()),
		// Keep the default detectors
		resource.WithTelemetrySDK(),
		// Add your own custom attributes to identify your application
		resource.WithAttributes(
			semconv.ServiceNameKey.String("my-application"),
		),
	)
	if errors.Is(err, resource.ErrPartialResource) || errors.Is(err, resource.ErrSchemaURLConflict) {
		log.Println(err)
	} else if err != nil {
		log.Fatalf("resource.New: %v", err)
	}

	// Create trace provider with the exporter.
	//
	// By default it uses AlwaysSample() which samples all traces.
	// In a production environment or high QPS setup please use
	// probabilistic sampling.
	// Example:
	//   tp := sdktrace.NewTracerProvider(sdktrace.WithSampler(sdktrace.TraceIDRatioBased(0.0001)), ...)
	tp := sdktrace.NewTracerProvider(
		sdktrace.WithBatcher(exporter),
		sdktrace.WithResource(res),
	)
	defer tp.Shutdown(ctx) // flushes any pending spans, and closes connections.
	otel.SetTracerProvider(tp)

	// Create custom span.
	tracer := otel.GetTracerProvider().Tracer("example.com/trace")
	err = func(ctx context.Context) error {
		ctx, span := tracer.Start(ctx, "foo")
		defer span.End()

		// Do some work.

		return nil
	}(ctx)
}

创建导出器时,您需要提供 Google Cloud 项目标识符的相关信息。在本示例中,标识符存储在环境变量 GOOGLE_CLOUD_PROJECT 中。

示例应用调用 WithBatcher 函数来配置跟踪记录提供程序,以使用后台进程将 span 发送到 Cloud Monitoring。此示例还配置为在应用退出时调用导出器的 Shutdown 函数。当 Shutdown 执行时,它会将所有待处理 span 发送到 Cloud Monitoring。示例中显示的配置是所有操作环境的推荐实现,包括可随时关停容器的 Cloud Run。

创建 Tracer 实例时,您需要为其提供一个名称。在示例中,名称为 example.com/trace。由于此策略使您可拥有多个实例,我们建议您按照所跟踪的组件来命名这些实例。

执行示例时,系统会创建一个名为 foo 的跟踪记录。

如何创建自定义 span

您可以通过创建自定义 span 来向系统创建的跟踪记录添加其他信息。

如需创建名为 foo 的自定义 span,请将以下内容添加到源代码中:

// Create custom span.
tracer := otel.GetTracerProvider().Tracer("example.com/trace")
err = func(ctx context.Context) error {
	ctx, span := tracer.Start(ctx, "foo")
	defer span.End()

	// Do some work.

	return nil
}(ctx)

在此处,example.com/trace 是指跟踪器实例的名称。

配置平台

您可以在 Google Cloud 和其他平台上使用 Cloud Trace。

在 Google Cloud 上运行

当您的应用在 Google Cloud 上运行时,您无需向客户端库提供服务账号形式的身份验证凭据。但是,您需要确保 Google Cloud Platform 已启用 Cloud Trace API 访问权限范围

如需查看受支持的 Google Cloud 环境的列表,请参阅环境支持

对于以下配置,默认的访问权限范围设置会启用 Cloud Trace API:

  • App Engine 柔性环境
  • App Engine 标准环境

  • Google Kubernetes Engine (GKE)

  • Compute Engine

  • Cloud Run

如果您使用自定义访问权限范围,则必须确保已启用 Cloud Trace API 访问权限范围

  • 如需了解如何使用 Google Cloud 控制台为您的环境配置访问权限范围,请参阅配置 Google Cloud 项目

  • 对于 gcloud 用户,请使用 --scopes 标志指定访问权限范围,并添加 trace.append Cloud Trace API 访问权限范围。例如,如需创建仅启用了 Cloud Trace API 的 GKE 集群,请执行以下操作:

    gcloud container clusters create example-cluster-name --scopes=https://www.googleapis.com/auth/trace.append

在本地和其他位置运行

如果您的应用在 Google Cloud 之外运行,则必须向客户端库提供服务账号形式的身份验证凭据。该服务账号必须包含 Cloud Trace Agent 角色。如需查看说明,请参阅创建服务账号

Google Cloud 客户端库使用应用默认凭据 (ADC) 查找应用的凭据。

您可以通过以下三种方式之一提供这些凭据:

  • 运行:gcloud auth application-default login

  • 将服务帐号放置在操作系统的默认路径中。 下面列出了 Windows 和 Linux 的默认路径:

    • Windows:%APPDATA%/gcloud/application_default_credentials.json

    • Linux:$HOME/.config/gcloud/application_default_credentials.json

  • GOOGLE_APPLICATION_CREDENTIALS 环境变量设置为您的服务帐号的路径:

Linux/macOS

    export GOOGLE_APPLICATION_CREDENTIALS=path-to-your-service-accounts-private-key

Windows

    set GOOGLE_APPLICATION_CREDENTIALS=path-to-your-service-accounts-private-key

PowerShell:

    $env:GOOGLE_APPLICATION_CREDENTIALS="path-to-your-service-accounts-private-key"

查看跟踪记录

在 Google Cloud 控制台的导航面板中,选择 Trace,然后选择 Trace 探索器

转到 Trace 探索器

问题排查

如需了解如何排查 Cloud Trace 的问题,请转到“问题排查”页面