

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 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)
+ [요청을 통한 발신 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. Python용 AWS Distro for OpenTelemetry(ADOT) 자동 계측 사용 - Python 애플리케이션에 대한 자동 계측은 [AWS Distro for OpenTelemetry Python 자동 계측을 사용한 추적 및 지표를 참조하세요](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`를 사용하면 애플리케이션의 모든 위치에서 스팬을 생성하는 데 사용할 수 있는 [Tracer](https://opentelemetry.io/docs/concepts/signals/traces/#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
```

------

**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 계측](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/wsgi/wsgi.html)을 사용하여 애플리케이션을 추적할 수 있습니다.

다음 코드 예제의 경우 다음 종속성이 필요합니다.

```
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 계측
<a name="aws-sdk-instrumentation-python"></a>

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

X-Ray Python SDK는 `botocore` 라이브러리를 패치하여 AWS SDK 클라이언트 요청을 추적합니다. 자세한 내용은 [Python용 X-Ray AWS SDK를 사용하여 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 계측](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}")
```

------

## 요청을 통한 발신 HTTP 직접 호출 계측
<a name="http-instrumentation-python"></a>

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

X-Ray Python SDK는 요청 라이브러리를 패치하여 요청을 통해 발신 HTTP 직접 호출을 추적합니다. 자세한 내용은 [Python용 X-Ray SDK를 사용하여 다운스트림 HTTP 웹 서비스에 대한 직접 호출 추적](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을 사용하여 요청 라이브러리를 계측함으로써 애플리케이션에서 수행한 HTTP 요청에 대한 추적을 생성합니다. 자세한 내용은 [OpenTelemetry 요청 계측](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>

[지원되는 라이브러리, 프레임워크, 애플리케이션 서버 및 JVM](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/docs/supported-libraries.md)에서 OpenTelemetry Python에 대해 지원되는 라이브러리 계측의 전체 목록을 찾을 수 있습니다.

또는 OpenTelemetry 레지스트리를 검색하여 OpenTelemetry가 계측을 지원하는지 확인할 수 있습니다. [레지스트리](https://opentelemetry.io/ecosystem/registry/)를 참조하여 검색을 시작합니다.

## 추적 데이터 수동 생성
<a name="manual-trace-creation-python"></a>

Python 애플리케이션에서 `xray_recorder`를 사용하여 세그먼트 및 하위 세그먼트를 생성할 수 있습니다. 자세한 내용은 [Python 코드 수동 계측](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를 사용하여 스팬을 시작하고 스팬을 생성하도록 설정합니다. 스팬 생성에 대한 예제는 [스팬 생성](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 계층을 사용하는 것이 좋습니다. 이렇게 하면 함수가 자동으로 계측되고 함수 간접 호출 및 함수의 다운스트림 요청에 대한 스팬이 생성됩니다. 추적 외에도 Application Signals를 사용하여 함수의 상태를 모니터링하는 데 관심이 있는 경우 [Lambda에서 애플리케이션 활성화](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Signals-Enable-LambdaMain.html)를 참조하세요.
+ [OpenTelemetry ARN용AWS Lambda 계층](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용 AWS Lambda 계층 자동 계측과 함께 `opentelemetry-api` 패키지만 사용하여 수행할 수 있습니다.

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