Go 및 OpenTelemetry

이 페이지는 OpenTelemetry를 사용하여 Go 애플리케이션용 Cloud Trace 데이터를 수집하려는 애플리케이션 개발자를 위해 설계되었습니다. OpenTelemetry는 trace 및 측정항목 데이터를 수집하는 데 사용할 수 있는 공급업체 중립적인 계측 프레임워크입니다. 코드 계측에 대한 자세한 내용은 계측 및 관측 가능성을 참조하세요.

  • OpenTelemetry 패키지를 설치합니다.
  • 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"
)

내보내기 및 trace 공급자를 만듭니다.

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 함수를 호출하여 백그라운드 프로세스를 통해 Cloud Monitoring에 스팬을 보내도록 trace 공급자를 구성합니다. 또한 이 예시에서는 애플리케이션 종료 시 내보내기 도구의 Shutdown 함수를 호출하도록 구성됩니다. Shutdown이 실행되면 대기 중인 모든 스팬을 Cloud Monitoring으로 보냅니다. 샘플에 표시된 구성은 컨테이너가 언제든지 종료될 수 있는 Cloud Run을 포함한 모든 운영 환경에 권장되는 구현입니다.

Tracer 인스턴스를 만들 때 이름을 지정합니다. 이 예시에서 이름은 example.com/trace입니다. 이 전략을 사용하면 여러 인스턴스를 사용할 수 있으므로 이러한 인스턴스의 이름은 추적되는 구성 요소의 이름을 따라 지정하는 것이 좋습니다.

예시가 실행되면 foo라는 단일 trace가 생성됩니다.

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"
)

내보내기 및 trace 공급자를 만듭니다.

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 함수를 호출하여 백그라운드 프로세스를 통해 Cloud Monitoring에 스팬을 보내도록 trace 공급자를 구성합니다. 또한 이 예시에서는 애플리케이션 종료 시 내보내기 도구의 Shutdown 함수를 호출하도록 구성됩니다. Shutdown이 실행되면 대기 중인 모든 스팬을 Cloud Monitoring으로 보냅니다. 샘플에 표시된 구성은 컨테이너가 언제든지 종료될 수 있는 Cloud Run을 포함한 모든 운영 환경에 권장되는 구현입니다.

Tracer 인스턴스를 만들 때 이름을 지정합니다. 이 예시에서 이름은 example.com/trace입니다. 이 전략을 사용하면 여러 인스턴스를 사용할 수 있으므로 이러한 인스턴스의 이름은 추적되는 구성 요소의 이름을 따라 지정하는 것이 좋습니다.

예시가 실행되면 foo라는 단일 trace가 생성됩니다.

커스텀 스팬을 만드는 방법

커스텀 스팬을 만들어 시스템 생성 trace에 정보를 추가할 수 있습니다.

foo라는 커스텀 스팬을 만들려면 소스 코드에 다음을 추가합니다.

// 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를 사용 설정합니다.

커스텀 액세스 범위를 사용하는 경우 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 에이전트 역할이 포함되어야 합니다. 자세한 내용은 서비스 계정 만들기를 참조하세요.

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"

trace 보기

Google Cloud 콘솔의 탐색 패널에서 Trace를 선택한 후 Trace 탐색기를 선택합니다.

Trace 탐색기로 이동

문제 해결

Cloud Trace 문제 해결에 대한 자세한 내용은 문제 해결 페이지를 참조하세요.