OpenTelemetry Python への移行 - AWS X-Ray

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

OpenTelemetry Python への移行

このガイドは、Python アプリケーションを X-Ray SDK から OpenTelemetry 計測に移行するのに役立ちます。自動計測アプローチと手動計測アプローチの両方を取り上げ、一般的なシナリオのコード例を示します。

ゼロコード自動計測ソリューション

X-Ray SDK では、リクエストをトレースするためにアプリケーションコードを変更する必要がありました。OpenTelemetry は、リクエストを追跡するためのゼロコード自動計測ソリューションを提供します。OpenTelemetry では、ゼロコード自動計測ソリューションを使用してリクエストをトレースできます。

OpenTelemetry ベースの自動計測を使用したゼロコード

  1. Distro for OpenTelemetry (ADOT) auto-Instrumentation for AWS Python – Python アプリケーションの自動計測については、AWS 「 Distro for OpenTelemetry Python Auto-Instrumentation」を参照してください。

    (オプション) ADOT Python 自動計測 AWS を使用して でアプリケーションを自動的に計測するときに CloudWatch Application Signals を有効にして、現在のアプリケーションの状態をモニタリングし、ビジネス目標に照らして長期的なアプリケーションパフォーマンスを追跡することもできます。Application Signals は、アプリケーション、サービス、依存関係をアプリケーション中心の統合ビューで表示し、アプリケーションの状態をモニタリングしてトリアージできるようにします。

  2. OpenTelemetry Python ゼロコード自動計測の使用 – OpenTelemetry Python を使用した自動計測については、「Python ゼロコード計測」を参照してください。

アプリケーションを手動で計測する

pip コマンドを使用して、アプリケーションを手動で計測できます。

With X-Ray SDK
pip install aws-xray-sdk
With OpenTelemetry SDK
pip install opentelemetry-api opentelemetry-sdk opentelemetry-exporter-otlp opentelemetry-propagator-aws-xray

トレース設定の初期化

With X-Ray SDK

X-Ray では、グローバルxray_recorderが初期化され、セグメントとサブセグメントを生成するために使用されます。

With OpenTelemetry SDK
注記

X-Ray リモートサンプリングは現在、OpenTelemetry Python 用に設定することはできません。ただし、現在、X-Ray リモートサンプリングのサポートは ADOT Auto-Instrumentation for Python を通じて利用できます。

OpenTelemetry では、グローバル を初期化する必要がありますTracerProvider。この を使用するとTracerProvider、アプリケーションの任意の場所でスパンを生成するために使用できる Tracer を取得できます。次のコンポーネントを設定することをお勧めします。

  • OTLPSpanExporter – CloudWatch エージェント/OpenTelemetry Collector へのトレースのエクスポートに必要です

  • AWS X-Ray プロパゲーター – X-Ray と統合された AWS サービスにトレースコンテキストを伝播するために必要です

from opentelemetry import ( trace, propagate ) from opentelemetry.sdk.trace import TracerProvider from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.propagators.aws import AwsXRayPropagator # Sends generated traces in the OTLP format to an OTel Collector running on port 4318 otlp_exporter = OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces") # Processes traces in batches as opposed to immediately one after the other span_processor = BatchSpanProcessor(otlp_exporter) # More configurations can be done here. We will visit them later. # Sets the global default tracer provider provider = TracerProvider(active_span_processor=span_processor) trace.set_tracer_provider(provider) # Configures the global propagator to use the X-Ray Propagator propagate.set_global_textmap(AwsXRayPropagator()) # Creates a tracer from the global tracer provider tracer = trace.get_tracer("my.tracer.name") # Use this tracer to create Spans

ADOT auto-Instrumentation for Python を使用する

ADOT auto-instrumentation for Python を使用して、Python アプリケーション用に OpenTelemetry を自動的に設定できます。ADOT 自動計測を使用すると、手動でコードを変更して受信リクエストをトレースしたり、 AWS SDK や HTTP クライアントなどのライブラリをトレースしたりする必要はありません。詳細については、AWS 「 Distro for OpenTelemetry Python Auto-Instrumentation を使用したトレースとメトリクス」を参照してください。

ADOT auto-instrumentation for Python は以下をサポートしています。

  • 環境変数を介した X-Ray リモートサンプリング export OTEL_TRACES_SAMPLER=xray

  • X-Ray トレースコンテキストの伝播 (デフォルトで有効)

  • リソース検出 (Amazon EC2、Amazon ECS、Amazon EKS 環境のリソース検出はデフォルトで有効になっています)

  • サポートされているすべての OpenTelemetry 計測の自動ライブラリ計測は、デフォルトで有効になっています。OTEL_PYTHON_DISABLED_INSTRUMENTATIONS 環境変数を使用して選択的に を無効にすることができます (すべてデフォルトで有効になっています)。

  • スパンの手動作成

X-Ray サービスプラグインから OpenTelemetry AWS リソースプロバイダーへ

X-Ray SDK には、Amazon EC2、Amazon ECS、Elastic Beanstalk などのホストされたサービスからプラットフォーム固有の情報をキャプチャxray_recorderするために に追加できるプラグインが用意されています。これは、情報をリソース属性としてキャプチャする OpenTelemetry のリソースプロバイダーに似ています。さまざまな AWS プラットフォームで使用できるリソースプロバイダーが複数あります。

  • まず、 AWS 拡張機能パッケージをインストールします。 pip install opentelemetry-sdk-extension-aws

  • 目的のリソースディテクターを設定します。次の例は、OpenTelemetry SDK で Amazon EC2 リソースプロバイダーを設定する方法を示しています。

    from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.extension.aws.resource.ec2 import ( AwsEc2ResourceDetector, ) from opentelemetry.sdk.resources import get_aggregated_resources provider = TracerProvider( active_span_processor=span_processor, resource=get_aggregated_resources([ AwsEc2ResourceDetector(), ])) trace.set_tracer_provider(provider)

受信リクエストのトレース

With X-Ray SDK

X-Ray Python SDK は、Django、Flask、Bottle などのアプリケーションフレームワークをサポートし、それらで実行されている Python アプリケーションの受信リクエストをトレースします。これは、各フレームワークの XRayMiddlewareをアプリケーションに追加することによって行われます。

With OpenTelemetry SDK

OpenTelemetry は、特定の計測ライブラリを通じて DjangoFlask の計測を提供します。OpenTelemetry で使用できる Bottle の計測はありません。OpenTelemetry WSGI Instrumentation を使用してアプリケーションを追跡できます。

次のコード例では、次の依存関係が必要です。

pip install opentelemetry-instrumentation-flask

アプリケーションフレームワークの計測を追加する前に、OpenTelemetry SDK を初期化し、グローバル TracerProvider を登録する必要があります。これを行わないと、トレースオペレーションは になりますno-ops。グローバル を設定したらTracerProvider、アプリケーションフレームワークにインストルメンタを使用できます。次の例は、Flask アプリケーションを示しています。

from flask import Flask from opentelemetry import trace from opentelemetry.instrumentation.flask import FlaskInstrumentor from opentelemetry.sdk.extension.aws.resource import AwsEc2ResourceDetector from opentelemetry.sdk.resources import get_aggregated_resources from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter provider = TracerProvider(resource=get_aggregated_resources( [ AwsEc2ResourceDetector(), ])) processor = BatchSpanProcessor(ConsoleSpanExporter()) provider.add_span_processor(processor) trace.set_tracer_provider(provider) # Creates a tracer from the global tracer provider tracer = trace.get_tracer("my.tracer.name") app = Flask(__name__) # Instrument the Flask app FlaskInstrumentor().instrument_app(app) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()

AWS SDK 計測

With X-Ray SDK

X-Ray Python SDK は、botocoreライブラリにパッチを適用して AWS SDK クライアントリクエストをトレースします。詳細については、「X-Ray AWS SDK for Python を使用した SDK 呼び出しのトレース」を参照してください。アプリケーションでは、 patch_all()メソッドを使用して、 または ライブラリを使用してすべてのboto3ライブラリbotocoreまたはパッチを選択的に計測しますpatch((['botocore']))。選択したメソッドのいずれかがアプリケーション内のすべての Boto3 クライアントを計測し、これらのクライアントを使用して行われた呼び出しのサブセグメントを生成します。

With OpenTelemetry SDK

次のコード例では、次の依存関係が必要です。

pip install opentelemetry-instrumentation-botocore

OpenTelemetry Botocore Instrumentation をプログラムで使用して、アプリケーション内のすべての Boto3 クライアントを計測します。次の例は、 botocoreインストルメンテーションを示しています。

import boto3 import opentelemetry.trace as trace from botocore.exceptions import ClientError from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.resources import get_aggregated_resources from opentelemetry.sdk.trace.export import ( BatchSpanProcessor, ConsoleSpanExporter, ) from opentelemetry.instrumentation.botocore import BotocoreInstrumentor provider = TracerProvider() processor = BatchSpanProcessor(ConsoleSpanExporter()) provider.add_span_processor(processor) trace.set_tracer_provider(provider) # Creates a tracer from the global tracer provider tracer = trace.get_tracer("my.tracer.name") # Instrument BotoCore BotocoreInstrumentor().instrument() # Initialize S3 client s3 = boto3.client("s3", region_name="us-east-1") # Your bucket name bucket_name = "my-example-bucket" # Get bucket location (as an example of describing it) try: response = s3.get_bucket_location(Bucket=bucket_name) region = response.get("LocationConstraint") or "us-east-1" print(f"Bucket '{bucket_name}' is in region: {region}") # Optionally, get bucket's creation date via list_buckets buckets = s3.list_buckets() for bucket in buckets["Buckets"]: if bucket["Name"] == bucket_name: print(f"Bucket created on: {bucket['CreationDate']}") break except ClientError as e: print(f"Failed to describe bucket: {e}")

リクエストによる送信 HTTP 呼び出しの計測

With X-Ray SDK

X-Ray Python SDK は、リクエストライブラリにパッチを適用して、リクエストを介して送信 HTTP 呼び出しをトレースします。詳細については、「X-Ray SDK for Python を使用したダウンストリーム HTTP ウェブサービスの呼び出しのトレース」を参照してください。アプリケーションでは、 patch_all()メソッドを使用してすべてのライブラリを計測するか、 を使用してリクエストライブラリに選択的にパッチを適用できますpatch((['requests']))。オプションのいずれかがrequestsライブラリを計測し、 を介して行われた呼び出しのサブセグメントを生成しますrequests

With OpenTelemetry SDK

次のコード例では、次の依存関係が必要です。

pip install opentelemetry-instrumentation-requests

OpenTelemetry Requests Instrumentation をプログラムで使用してリクエストライブラリを計測し、アプリケーション内でリクエストによって行われた HTTP リクエストのトレースを生成します。詳細については、OpenTelemetry requests Instrumentation」を参照してください。次の例は、requestsライブラリの計測を示しています。

from opentelemetry.instrumentation.requests import RequestsInstrumentor # Instrument Requests RequestsInstrumentor().instrument() ... example_session = requests.Session() example_session.get(url="https://example.com")

または、基盤となるurllib3ライブラリを計測して HTTP リクエストをトレースすることもできます。

# pip install opentelemetry-instrumentation-urllib3 from opentelemetry.instrumentation.urllib3 import URLLib3Instrumentor # Instrument urllib3 URLLib3Instrumentor().instrument() ... example_session = requests.Session() example_session.get(url="https://example.com")

他のライブラリの計測サポート

OpenTelemetry Python でサポートされているライブラリ計測の完全なリストは、サポートされているライブラリ、フレームワーク、アプリケーションサーバー、および JVMsにあります。

または、OpenTelemetry Registry を検索して、OpenTelemetry が計測をサポートしているかどうかを調べることもできます。検索を開始するには、 レジストリを参照してください。

トレースデータを手動で作成する

Python アプリケーションの xray_recorder を使用してセグメントとサブセグメントを作成できます。詳細については、「Python コードの手動計測」を参照してください。トレースデータに注釈とメタデータを手動で追加することもできます。

OpenTelemetry SDK を使用したスパンの作成

start_as_current_span API を使用してスパンを開始し、スパンを作成するための設定を行います。スパンの作成例については、「スパンの作成」を参照してください。スパンが開始され、現在のスコープに入ると、属性、イベント、例外、リンクなどを追加して、スパンに詳細情報を追加できます。X-Ray にセグメントとサブセグメントがある場合と同様に、OpenTelemetry にはさまざまな種類のスパンがあります。SERVER 種類スパンのみが X-Ray セグメントに変換され、その他は X-Ray サブセグメントに変換されます。

from opentelemetry import trace from opentelemetry.trace import SpanKind import time tracer = trace.get_tracer("my.tracer.name") # Create a new span to track some work with tracer.start_as_current_span("parent", kind=SpanKind.SERVER) as parent_span: time.sleep(1) # Create a nested span to track nested work with tracer.start_as_current_span("child", kind=SpanKind.CLIENT) as child_span: time.sleep(2) # the nested span is closed when it's out of scope # Now the parent span is the current span again time.sleep(1) # This span is also closed when it goes out of scope

OpenTelemetry SDK を使用してトレースに注釈とメタデータを追加する

X-Ray Python SDK には、トレースに注釈とメタデータを追加put_metadataするための個別の APIs put_annotationと が用意されています。OpenTelemetry SDK では、注釈とメタデータは単にスパンの属性であり、set_attributeAPI を介して追加されます。

トレースの注釈にするスパン属性は、予約キーの下に追加されます。aws.xray.annotations予約キーの値は注釈のキーと値のペアのリストです。他のすべてのスパン属性は、変換されたセグメントまたはサブセグメントのメタデータになります。

さらに、ADOT コレクターを使用している場合は、コレクター設定indexed_attributesで を指定することで、X-Ray 注釈に変換するスパン属性を設定できます。

次の例は、OpenTelemetry SDK を使用してトレースに注釈とメタデータを追加する方法を示しています。

with tracer.start_as_current_span("parent", kind=SpanKind.SERVER) as parent_span: parent_span.set_attribute("TransactionId", "qwerty12345") parent_span.set_attribute("AccountId", "1234567890") # This will convert the TransactionId and AccountId to be searchable X-Ray annotations parent_span.set_attribute("aws.xray.annotations", ["TransactionId", "AccountId"]) with tracer.start_as_current_span("child", kind=SpanKind.CLIENT) as child_span: # The MicroTransactionId will be converted to X-Ray metadata for the child subsegment child_span.set_attribute("MicroTransactionId", "micro12345")

Lambda 計測

X-Ray で Lambda 関数をモニタリングするには、X-Ray を有効にし、関数呼び出しロールに適切なアクセス許可を追加しました。さらに、関数からのダウンストリームリクエストをトレースする場合は、X-Ray Python SDK を使用してコードを計測します。

OpenTelemetry for X-Ray では、Application Signals をオフにして CloudWatch Application Signals Lambda レイヤーを使用することをお勧めします。これにより、関数が自動計測され、関数の呼び出しと関数からのダウンストリームリクエストのスパンが生成されます。トレースに加えて、Application Signals を使用して関数の状態をモニタリングする場合は、「Lambda でアプリケーションを有効にする」を参照してください。

Lambda 計測を使用したスパンの手動作成

さらに、 関数内でカスタムスパンを生成して作業を追跡できます。これを行うには、Application Signals Lambda レイヤーの自動計測と組み合わせて opentelemetry-apiパッケージのみを使用します。

  1. 関数の依存関係opentelemetry-apiとして を含める

  2. 次のコードスニペットは、カスタムスパンを生成するためのサンプルです。

    from opentelemetry import trace # Get the tracer (auto‑configured by the Application Signals layer) tracer = trace.get_tracer(__name__) def handler(event, context): # This span is a child of the layer's root span with tracer.start_as_current_span("my-custom-span") as span: span.set_attribute("key1", "value1") span.add_event("custom-event", {"detail": "something happened"}) # Any logic you want to trace result = some_internal_logic() return { "statusCode": 200, "body": result }