Zenn
🔭

Cloud Trace でネイティブの OpenTelemetry を利用できる Telemetry API を試してみる

に公開

最近気になるリリースが出ていました。

https://cloud.google.com/stackdriver/docs/reference/telemetry/overview?hl=ja

Google Cloud でのトレースを可視化するには Cloud Trace を利用する必要があります。

Cloud Trace にトレースを送信するには Cloud Trace 用の exporter を利用する必要がありました。

しかし、 Telemetry API の登場により Cloud Trace に依存した実装から OpenTelemetry 準拠の実装を利用して Cloud Trace にトレースを送信できるようになりました。

以下の移行ドキュメントでは環境変数などを併用して実装してありますが、今回は全て Go の実装側に寄せて実装してみます。

https://cloud.google.com/stackdriver/docs/instrumentation/migrate-to-otlp-endpoints?hl=ja#telemetry_add_dependencies-go

前提

Telemetry API を有効化します。

https://console.cloud.google.com/apis/library/telemetry.googleapis.com

実装

Exporter

OTLP で利用する exporter を作成します。

  1. Telemetry API のエンドポイント ( telemetry.googleapis.com:443 ) を指定します。
  2. grpc.WithPerRPCCredentials を使って認証情報を指定します。
    今回は Cloud Run 上でアプリケーションを実行するので、 oauth.NewApplicationDefault を使って認証情報を取得します。
// "context"
// "google.golang.org/grpc/credentials/oauth"
// "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
// "google.golang.org/grpc"
// "go.uber.org/zap"
// "go.uber.org/zap/zapcore"

ctx := context.Background()

core := zapcore.NewCore(...)
l := zap.New(core)

cred, err := oauth.NewApplicationDefault(ctx)
if err != nil {
	l.Panic(err.Error())
}

exporter, err := otlptracegrpc.New(
	ctx,
	otlptracegrpc.WithDialOption(grpc.WithPerRPCCredentials(cred)),
	otlptracegrpc.WithEndpoint("telemetry.googleapis.com:443"),
)

Tracer

先ほど作成した exporter を利用して Tracer を作成します。

// semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
// "go.opentelemetry.io/otel/sdk/resource"
// "go.opentelemetry.io/otel/attribute"
// "go.opentelemetry.io/otel"

rs, err := resource.New(
	ctx,
	resource.WithAttributes(
		semconv.ServiceNameKey.String("SERVICE_NAME"),
		attribute.String("gcp.project_id", "PROJECT_ID"),
	),
)
if err != nil {
	l.Panic(err.Error())
}

tp := sdktrace.NewTracerProvider(
	sdktrace.WithBatcher(exporter),
	sdktrace.WithResource(rs),
)
defer func() {
	if err := tp.Shutdown(context.Background()); err != nil {
		l.Panic(err.Error())
	}
}()

otel.SetTracerProvider(tp)

利用方法

あとは通常の OpenTelemetry と同様に利用できます。

ctx, span := otel.Tracer("main").Start(ctx, "span")

あとは Cloud Trace で可視化できます。

まとめ

Telemetry API を利用することで、Cloud Trace に依存した実装から OpenTelemetry 準拠の実装に移行できるようになりました。

FAQ

Resource is missing gcp.project_id resource attribute

Resource attribute に gcp.project_id を指定する必要があります。

2025/04/12 07:32:17 traces export: rpc error: code = InvalidArgument desc = Resource is missing gcp.project_id resource attribute

Header の x-goog-user-project

https://cloud.google.com/stackdriver/docs/instrumentation/migrate-to-otlp-endpoints?hl=ja#otel-attrs

Telemetry API を利用するためのプロジェクトを指定できます。
指定しない場合でも動作自体は問題ありません。

Discussion

ログインするとコメントできます