

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

# OpenTelemetry Python への移行
<a name="migrate-xray-to-opentelemetry-python"></a>

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

**Topics**
+ [ゼロコード自動計装ソリューション](#zero-code-python)
+ [アプリケーションを手動で計装する](#manual-instrumentation-python)
+ [トレースセットアップの初期化](#manual-instrumentation-python-tracing)
+ [受信リクエストのトレース](#tracing-incoming-requests-python)
+ [AWS SDK 計測](#aws-sdk-instrumentation-python)
+ [requests による送信 HTTP 呼び出しの計装](#http-instrumentation-python)
+ [他のライブラリの計装サポート](#xray-migration-libraries-python)
+ [トレースデータを手動で作成する](#manual-trace-creation-python)
+ [Lambda 計装](#lambda-instrumentation-python)

## ゼロコード自動計装ソリューション
<a name="zero-code-python"></a>

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

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

1. Distro for OpenTelemetry (ADOT) auto-Instrumentation for AWS Python – Python アプリケーションの自動計測については、[AWS 「 Distro for OpenTelemetry Python Auto-Instrumentation](https://aws-otel.github.io/docs/getting-started/python-sdk/auto-instr)」を参照してください。

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

1. OpenTelemetry Python のゼロコード自動計装の使用 – OpenTelemetry Python を使用した自動計装については、「[Python ゼロコード計装](https://opentelemetry.io/docs/zero-code/python/)」を参照してください。

## アプリケーションを手動で計装する
<a name="manual-instrumentation-python"></a>

`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
```

------

## トレースセットアップの初期化
<a name="manual-instrumentation-python-tracing"></a>

------
#### [ With X-Ray SDK ]

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

------
#### [ With OpenTelemetry SDK ]

**注記**  
X-Ray リモートサンプリングは現在、OpenTelemetry Python 用に設定することはできません。ただし、X-Ray リモートサンプリングのサポートは、Python の ADOT 自動計装を通じて現在も利用できます。

OpenTelemetry では、グローバルな `TracerProvider` を初期化する必要があります。この `TracerProvider` を使用すると、アプリケーションの任意の場所でスパンを生成するために使用できる[トレーサー](https://opentelemetry.io/docs/concepts/signals/traces/#tracer)を取得できます。以下のコンポーネントを設定することをお勧めします。
+ `OTLPSpanExporter` – CloudWatch エージェント/OpenTelemetry コレクターへのトレースのエクスポートに必要です。
+  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
```

------

**Python 用の ADOT 自動計装の使用**

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

Python 用の ADOT 自動計装は以下をサポートしています。
+ 環境変数 `export OTEL_TRACES_SAMPLER=xray` を介した X-Ray リモートサンプリング
+ 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)
  ```

## 受信リクエストのトレース
<a name="tracing-incoming-requests-python"></a>

------
#### [ With X-Ray SDK ]

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

------
#### [ With OpenTelemetry SDK ]

OpenTelemetry は、特定の計装ライブラリを通じて [Django](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/django/django.html) と [Flask](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/flask/flask.html) の計装を提供しています。OpenTelemetry で使用できる Bottle の計装はありません。[OpenTelemetry WSGI Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/wsgi/wsgi.html) を使用してアプリケーションを追跡できます。

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

```
pip install opentelemetry-instrumentation-flask
```

アプリケーションフレームワークの計装を追加する前に、OpenTelemetry SDK を初期化し、グローバルな TracerProvider を登録する必要があります。これを行わないと、トレースオペレーションは `no-ops` になります。グローバルな `TracerProvider` を設定したら、アプリケーションフレームワークに Instrumentor を使用できます。次の例は、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 計測
<a name="aws-sdk-instrumentation-python"></a>

------
#### [ With X-Ray SDK ]

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

------
#### [ With OpenTelemetry SDK ]

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

```
pip install opentelemetry-instrumentation-botocore
```

[OpenTelemetry Botocore Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/botocore/botocore.html) をプログラムで使用して、アプリケーション内のすべての 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}")
```

------

## requests による送信 HTTP 呼び出しの計装
<a name="http-instrumentation-python"></a>

------
#### [ With X-Ray SDK ]

X-Ray Python SDK は、requests ライブラリにパッチを適用して、リクエストを通じて送信 HTTP 呼び出しをトレースします。詳細については、「[Tracing calls to downstream HTTP web services using the X-Ray SDK for Python](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-python-httpclients.html)」を参照してください。アプリケーションでは、`patch_all()` メソッドを使用してすべてのライブラリを計装するか、`patch((['requests']))` を使用してリクエストライブラリに選択的にパッチを適用できます。オプションのいずれかが `requests` ライブラリを計装し、`requests` を介して行われた呼び出しのサブセグメントを生成します。

------
#### [ With OpenTelemetry SDK ]

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

```
pip install opentelemetry-instrumentation-requests
```

OpenTelemetry Requests Instrumentation をプログラムで使用して、requests ライブラリを計装し、アプリケーションで OpenTelemetry Requests によって行われた HTTP リクエストのトレースを生成します。詳細については、「[OpenTelemetry requests Instrumentation](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/requests/requests.html)」を参照してください。次の例は、`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")
```

------

## 他のライブラリの計装サポート
<a name="xray-migration-libraries-python"></a>

OpenTelemetry Python でサポートされているライブラリ計装の全リストは、「[Supported libraries, frameworks, application servers, and JVMs](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/docs/supported-libraries.md)」にあります。

または、OpenTelemetry レジストリを検索して、OpenTelemetry が計装をサポートしているかどうかを調べることもできます。検索を開始するには、「[Registry](https://opentelemetry.io/ecosystem/registry/)」を参照してください。

## トレースデータを手動で作成する
<a name="manual-trace-creation-python"></a>

Python アプリケーションで `xray_recorder` を使用してセグメントとサブセグメントを作成できます。詳細については、「[Instrumenting Python code manually](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-python-middleware.html#xray-sdk-python-middleware-manual)」を参照してください。トレースデータに注釈とメタデータを手動で追加することもできます。

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

`start_as_current_span` API を使用してスパンを開始し、スパンを作成するための設定を行います。スパンの作成例については、「[Creating spans](https://opentelemetry.io/docs/languages/python/instrumentation/#creating-spans)」を参照してください。スパンを開始し、現在のスコープに入ると、属性、イベント、例外、リンクなどを追加して、スパンに詳細情報を追加できます。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 には、トレースに注釈とメタデータを追加するための個別の API、`put_annotation` と `put_metadata` が用意されています。OpenTelemetry SDK では、注釈とメタデータは単にスパンの属性であり、`set_attribute` API を介して追加されます。

トレースの注釈にするスパン属性は、予約キー `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 計装
<a name="lambda-instrumentation-python"></a>

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

OpenTelemetry for X-Ray では、[Application Signals](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-application-signals.html) をオフにした状態で OpenTelemetry 用の AWS Lambda Layer を使用することをお勧めします。これにより、関数が自動計装され、関数の呼び出しと関数からのダウンストリームリクエストのスパンが生成されます。トレースに加えて、Application Signals を使用して関数の状態をモニタリングする場合は、「[Lambda でアプリケーションを有効にする](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Signals-Enable-LambdaMain.html)」を参照してください。
+ [AWS Lambda Layer for OpenTelemetry ARN](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Signals-Enable-LambdaMain.html#Enable-Lambda-Layers) から関数に必要な Lambda レイヤー ARN を見つけて追加します。
+ これを行うには、関数に次の環境変数を設定します。
  + `AWS_LAMBDA_EXEC_WRAPPER=/opt/otel-instrument` – 関数の自動計装をロードします。
  + `OTEL_AWS_APPLICATION_SIGNALS_ENABLED=false` – これにより、Application Signals のモニタリングが無効になります。

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

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

1. 関数の依存関係として `opentelemetry-api` を含めます。

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

   ```
   from opentelemetry import trace
   
   # Get the tracer (auto‑configured by the AWS Lambda Layer for OpenTelemetry)
   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
       }
   ```