Zenn
🔗

Go で Google Cloud Logging と Cloud Trace でログとトレースを紐付ける

に公開

いつも忘れるのでメモ。

はじめに

タイトルの通り、 Go で Google Cloud Logging と Cloud Trace でログとトレースを紐付けるための実装方法を記載する。

前提

Cloud Logging ではいくつかの予約フィールドが存在する。

https://cloud.google.com/logging/docs/structured-logging#structured_logging_special_fields

この中の以下のフィールドに必要な情報を設定することで Google Cloud の Cloud Logging と Cloud Trace でログとトレースを紐付けることができる。

  • logging.googleapis.com/spanId
    • 例 : "logging.googleapis.com/spanId":"000000000000004a"
  • logging.googleapis.com/trace
    • 例 : "logging.googleapis.com/trace":"projects/my-projectid/traces/0679686673a"
  • logging.googleapis.com/trace_sampled
    • 例 : "logging.googleapis.com/trace_sampled":"true"

それぞれのロガーで上記のフィールドに必要な情報を付与するような実装を追加してあげる。

実装

いくつかのロガーごとに実装例を列挙しておく。

Zap

https://github.com/uber-go/zap

import (
	"go.uber.org/zap"
	"go.opentelemetry.io/otel"
)

func main() {
	l := zap.NewProduction() // 適宜ロガーを初期化する
	_, span := otel.Tracer("main").Start(context.Background(), "main")
	l.Info(
		"main",
		// PROJECT_ID は自身のプロジェクト ID に置き換える
		zap.String("logging.googleapis.com/trace", fmt.Sprintf("projects/%s/traces/%s", "PROJECT_ID", span.SpanContext().TraceID().String())),
		zap.String("logging.googleapis.com/spanId", span.SpanContext().SpanID().String()),
		zap.Bool("logging.googleapis.com/trace_sampled", span.SpanContext().IsSampled()),
	)
}

slog

WIP

動作確認

Cloud Logging からは Cloud Trace へのリンクが表示される。

Cloud Trace からは対象のトレースを選択すると「ログとイベント」に該当のログが表示される。

Discussion

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