Python 및 OpenTelemetry

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

  • OpenTelemetry 패키지를 설치합니다.
  • Cloud Trace로 스팬을 내보내도록 애플리케이션을 구성합니다.
  • 플랫폼을 구성합니다.

출시 정보는 다음을 참조하세요.

OpenTelemetry 참조 콘텐츠는 다음을 확인하세요.

Python용 OpenTelemetry에 대한 최신 세부정보 및 추가 문서와 예시는 OpenTelemetry를 참조하세요.

시작하기 전에

  • Python 3.6 이상을 사용해야 합니다.
  • Google Cloud 콘솔의 탐색 패널에서 API 및 서비스를 선택하고 API 및 서비스 사용 설정을 클릭한 다음 Cloud Trace API를 사용 설정합니다.

    Cloud Trace API 설정으로 이동

  • API 사용 설정됨이 표시되어 있으면 API가 이미 사용 설정된 것입니다. 그렇지 않으면 사용 설정 버튼을 클릭합니다.

OpenTelemetry 패키지 설치

필요한 OpenTelemetry 패키지를 설치하려면 다음을 수행합니다.

  1. (선택사항) pip를 최신 버전으로 업그레이드합니다.

    pip install --upgrade pip
    
  2. pip를 사용하여 다음 OpenTelemetry 패키지를 설치합니다.

    pip install opentelemetry-api \
      opentelemetry-sdk \
      opentelemetry-exporter-gcp-trace
    

trace 패키지 가져오기

다음 패키지와 클래스를 가져오도록 애플리케이션을 업데이트합니다.

  • trace
  • CloudTraceSpanExporter
  • TracerProvider
  • BatchSpanProcessor는 백그라운드 프로세스를 사용하여 스팬을 전송하는 내보내기 스팬 프로세서입니다.

  • (선택사항) 스팬을 연결하려면 Link 클래스를 가져옵니다.

다음 예시에서는 이러한 가져오기 문을 보여줍니다.


from opentelemetry import trace
from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.trace import Link

Cloud Trace로 스팬 내보내기 구성

스팬을 Cloud Trace로 보내려면 CloudTraceSpanExporter 내보내기 도구를 사용하도록 애플리케이션을 수정합니다. 다음은 필요한 단계를 보여주는 예시입니다.


tracer_provider = TracerProvider()
cloud_trace_exporter = CloudTraceSpanExporter()
tracer_provider.add_span_processor(
    # BatchSpanProcessor buffers spans and sends them in batches in a
    # background thread. The default parameters are sensible, but can be
    # tweaked to optimize your performance
    BatchSpanProcessor(cloud_trace_exporter)
)
trace.set_tracer_provider(tracer_provider)

tracer = trace.get_tracer(__name__)

스팬에 속성 추가

스팬에 속성을 추가하려면 스팬의 set_attribute 메서드를 호출합니다. 예를 들어 다음 코드는 foo_with_attribute라는 스팬에 속성 여러 개를 추가합니다.


with tracer.start_span("foo_with_attribute") as current_span:
    do_work()

    # Add attributes to the spans of various types
    current_span.set_attribute("string_attribute", "str")
    current_span.set_attribute("bool_attribute", False)
    current_span.set_attribute("int_attribute", 3)
    current_span.set_attribute("float_attribute", 3.14)

스팬에 이벤트 추가

스팬에 이벤트를 추가하려면 스팬의 add_event 메서드를 호출합니다. 예를 들어 다음 코드는 foo_with_event라는 스팬에 이벤트를 추가합니다.


# Adding events to spans
with tracer.start_as_current_span("foo_with_event") as current_span:
    do_work()
    current_span.add_event(name="event_name")

스팬 두 개를 연결하려면 Link 클래스를 가져온 후 start_as_current_span 메서드의 links 필드를 사용합니다. 스팬 두 개를 연결하면 links 필드에 속성을 포함할 수 있습니다.

다음 코드에서는 스팬을 link_target이라는 스팬에 연결할 수 있는 두 가지 방법을 보여줍니다.


# Adding links to spans
with tracer.start_as_current_span("link_target") as link_target:
    # Using start_as_current_span() instead of start_span() will make spans
    # created within this scope children of foo_with_attribute

    # Creates a span "span_with_link" and a link from
    # "span_with_link" -> "link_target"
    with tracer.start_as_current_span(
        "span_with_link", links=[Link(link_target.context)]
    ):
        do_work()

    # Creates a span "span_with_link" and a link from
    # "span_with_link" -> "link_target". This link also has the attribute
    # {"link_attr": "string"}
    with tracer.start_as_current_span(
        "span_with_link_and_link_attributes",
        links=[Link(link_target.context, attributes={"link_attr": "string"})],
    ):
        do_work()

샘플 Flask 애플리케이션

OpenTelemetry의 Flask 계측은 HTTP 요청과 관련된 trace 콘텐츠를 간단하게 캡처하도록 설계되었습니다. 즉, 이러한 요청에 대한 특정 계측을 경로에 추가할 필요가 없습니다.

  • Flask는 구성된 전파를 사용하여 들어오는 HTTP 요청에서 스팬 컨텍스트를 추출합니다.
  • Flask는 요청과 응답을 설명하는 속성을 사용하여 자동으로 스팬을 만듭니다.

Flask 및 OpenTelemetry를 사용하는 엔드 투 엔드 예시는 flask_e2e를 참조하세요. Git README에는 예시를 설치, 구성, 실행하는 방법에 대한 정보가 포함되어 있습니다.

이 섹션에서는 예시의 server.py 파일에 포함된 Flask별 구성 단계를 보여줍니다. 클라이언트 파일 client.pyRequests 계측을 사용하여 요청 라이브러리에서 생성된 HTTP 요청을 추적할 수 있습니다.

가져오기 및 구성

OpenTelemetry의 Flask 계측을 사용하려면 FlaskInstrumentor를 가져와야 합니다.

다른 Google Cloud 제품에서 생성된 스팬이 동일한 trace에 연결되도록 하려면 Cloud Trace 전파를 사용하여 전파를 구성해야 합니다. 이 전파는 X-Cloud-Trace-Context 헤더 사용을 지정합니다. 전파를 구성하지 않으면 OpenTelemetry는 기본 전파를 사용합니다. 이 경우 Cloud Run 및 App Engine과 같은 다른 Google Cloud 제품에서 생성된 스팬은 별도의 trace에 있습니다.

다음 샘플에서는 필수 가져오기 및 구성 문, Cloud Trace 전파 구성을 보여줍니다.


import time

from flask import Flask
from opentelemetry import metrics, trace
from opentelemetry.exporter.cloud_monitoring import (
    CloudMonitoringMetricsExporter,
)
from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry.propagate import set_global_textmap
from opentelemetry.propagators.cloud_trace_propagator import (
    CloudTraceFormatPropagator,
)
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

set_global_textmap(CloudTraceFormatPropagator())

CloudTraceSpanExporter 내보내기 도구를 구성할 때 Flask별 문을 추가할 필요가 없습니다. Cloud Trace로 스팬 내보내기 구성에 나오는 구성만으로도 충분합니다.

Flask 초기화

FlaskInstrumentor를 구성하여 애플리케이션을 계측합니다. 다음 샘플에서는 이 단계를 수행하는 방법을 보여줍니다.


app = Flask(__name__)
FlaskInstrumentor().instrument_app(app)

@app.route("/")
def hello_world():
    # You can still use the OpenTelemetry API as usual to create custom spans
    # within your trace
    with tracer.start_as_current_span("do_work"):
        time.sleep(0.1)

    return "Hello, World!"

플랫폼 구성

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 문제 해결에 대한 자세한 내용은 문제 해결 페이지를 참조하세요.

리소스