

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Migrare a Python OpenTelemetry
<a name="migrate-xray-to-opentelemetry-python"></a>

Questa guida ti aiuta a migrare le applicazioni Python da X-Ray SDK alla strumentazione. OpenTelemetry Copre approcci di strumentazione sia automatici che manuali, con esempi di codice per scenari comuni.

**Topics**
+ [Soluzioni di strumentazione automatica a codice zero](#zero-code-python)
+ [Strumenta manualmente le tue applicazioni](#manual-instrumentation-python)
+ [Tracciamento dell'inizializzazione della configurazione](#manual-instrumentation-python-tracing)
+ [Tracciamento delle richieste in arrivo](#tracing-incoming-requests-python)
+ [AWS Strumentazione SDK](#aws-sdk-instrumentation-python)
+ [Strumentazione delle chiamate HTTP in uscita tramite richieste](#http-instrumentation-python)
+ [Supporto strumentale per altre librerie](#xray-migration-libraries-python)
+ [Creazione manuale di dati di traccia](#manual-trace-creation-python)
+ [Strumentazione Lambda](#lambda-instrumentation-python)

## Soluzioni di strumentazione automatica a codice zero
<a name="zero-code-python"></a>

Con X-Ray SDK, era necessario modificare il codice dell'applicazione per tracciare le richieste. OpenTelemetry offre soluzioni di strumentazione automatica a codice zero per tracciare le richieste. Con OpenTelemetry, hai la possibilità di utilizzare soluzioni di strumentazione automatica a codice zero per tracciare le richieste.

**Codice zero con strumentazione automatica basata OpenTelemetry**

1. [Utilizzo della strumentazione automatica AWS Distro for OpenTelemetry (ADOT) per Python — Per la strumentazione automatica per le applicazioni Python, vedi Tracing and Metrics with the Distro for Python Auto-Instrumentation. AWS OpenTelemetry ](https://aws-otel.github.io/docs/getting-started/python-sdk/auto-instr)

   (Facoltativo) È inoltre possibile abilitare CloudWatch Application Signals durante la strumentazione automatica delle applicazioni AWS con la strumentazione automatica ADOT Python per monitorare lo stato attuale delle applicazioni e tenere traccia delle prestazioni delle applicazioni a lungo termine rispetto agli obiettivi aziendali. Application Signals ti offre una visione unificata e incentrata sulle applicazioni di applicazioni, servizi e dipendenze e ti aiuta a monitorare e valutare lo stato delle applicazioni.

1. [Utilizzo della strumentazione automatica OpenTelemetry Python a codice zero — Per la strumentazione automatica con Python, vedi Strumentazione Python a codice zero. OpenTelemetry ](https://opentelemetry.io/docs/zero-code/python/)

## Strumenta manualmente le tue applicazioni
<a name="manual-instrumentation-python"></a>

È possibile strumentare manualmente le applicazioni utilizzando il comando. `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
```

------

## Tracciamento dell'inizializzazione della configurazione
<a name="manual-instrumentation-python-tracing"></a>

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

In X-Ray, il globale `xray_recorder` viene inizializzato e utilizzato per generare segmenti e sottosegmenti.

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

**Nota**  
X-Ray Remote Sampling non è attualmente disponibile per la configurazione per Python. OpenTelemetry Tuttavia, il supporto per il campionamento remoto a raggi X è attualmente disponibile tramite ADOT Auto-Instrumentation for Python.

Nel, è necessario inizializzare un OpenTelemetry file globale. `TracerProvider` In questo modo`TracerProvider`, è possibile acquisire un [Tracer](https://opentelemetry.io/docs/concepts/signals/traces/#tracer) che è possibile utilizzare per generare intervalli in qualsiasi punto dell'applicazione. Si consiglia di configurare i seguenti componenti:
+ `OTLPSpanExporter`— Necessario per esportare le tracce nell' CloudWatch OpenTelemetry Agent/ Collector
+ Un propagatore AWS a raggi X: necessario per propagare il Trace Context ai AWS servizi integrati con X-Ray

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

------

**Con strumentazione automatica ADOT per Python**

Puoi usare la strumentazione automatica ADOT per Python per configurare OpenTelemetry automaticamente le tue applicazioni Python. Utilizzando la strumentazione automatica ADOT, non è necessario apportare modifiche manuali al codice per tracciare le richieste in arrivo o tracciare librerie come i AWS client SDK o HTTP. Per ulteriori informazioni, consulta [Tracciamento e metriche con la distribuzione AWS per Python OpenTelemetry Auto-Instrumentation](https://aws-otel.github.io/docs/getting-started/python-sdk/auto-instr).

La strumentazione automatica ADOT per Python supporta:
+ Campionamento remoto a raggi X tramite la variabile di ambiente `export OTEL_TRACES_SAMPLER=xray`
+ Propagazione contestuale delle tracce X-Ray (abilitata per impostazione predefinita)
+ Rilevamento delle risorse (il rilevamento delle risorse per gli ambienti Amazon EC2, Amazon ECS e Amazon EKS è abilitato per impostazione predefinita)
+ Le strumentazioni di libreria automatiche per tutte le strumentazioni supportate sono abilitate per OpenTelemetry impostazione predefinita. È possibile disabilitarla in modo selettivo tramite la variabile di ambiente. `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS ` (tutti sono abilitati di default)
+ Creazione manuale di Spans

**Dai plug-in dei servizi X-Ray ai provider di risorse OpenTelemetry AWS **

L'X-Ray SDK fornisce plug-in che è possibile aggiungere per acquisire informazioni specifiche sulla piattaforma dal servizio ospitato come Amazon EC2, Amazon ECS ed Elastic Beanstalk. `xray_recorder` È simile ai Resource Providers in quanto acquisisce le informazioni come attributi di risorse. OpenTelemetry Sono disponibili più Resource Provider per diverse AWS piattaforme.
+ Inizia installando il pacchetto di AWS estensione, `pip install opentelemetry-sdk-extension-aws`
+ Configura il rilevatore di risorse desiderato. L'esempio seguente mostra come configurare il provider di risorse Amazon EC2 in SDK. OpenTelemetry 

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

## Tracciamento delle richieste in arrivo
<a name="tracing-incoming-requests-python"></a>

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

L'X-Ray Python SDK supporta framework applicativi come Django, Flask e Bottle per tracciare le richieste in arrivo per le applicazioni Python in esecuzione su di essi. Questo viene fatto aggiungendo all'applicazione per ogni framework. `XRayMiddleware`

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

OpenTelemetry fornisce strumentazioni per [Django](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/django/django.html) e [Flask](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/flask/flask.html) attraverso le librerie di strumentazione specifiche. [Non è disponibile alcuna strumentazione per Bottle OpenTelemetry, le applicazioni possono ancora essere tracciate utilizzando la strumentazione WSGI. OpenTelemetry ](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/wsgi/wsgi.html)

Per il seguente esempio di codice, è necessaria la seguente dipendenza:

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

È necessario inizializzare l' OpenTelemetry SDK e registrare quello globale TracerProvider prima di aggiungere strumentazioni per il framework dell'applicazione. Senza di essa, le operazioni di tracciamento lo saranno. `no-ops` Dopo aver configurato il globale`TracerProvider`, è possibile utilizzare lo strumentor per il framework dell'applicazione. L'esempio seguente mostra un'applicazione 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 Strumentazione SDK
<a name="aws-sdk-instrumentation-python"></a>

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

L'X-Ray Python SDK traccia la richiesta del client SDK applicando una AWS patch alla libreria. `botocore` Per ulteriori informazioni, consulta [Tracciare le chiamate AWS SDK con l'SDK X-Ray](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-python-awssdkclients.html) per Python. Nell'applicazione, il `patch_all()` metodo viene utilizzato per strumentare tutte le librerie o applicare le patch in modo selettivo utilizzando le librerie or. `botocore` `boto3` `patch((['botocore']))` Qualsiasi metodo scelto monitora tutti i client Boto3 dell'applicazione e genera un sottosegmento per ogni chiamata effettuata utilizzando questi client.

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

Per il seguente esempio di codice, avrai bisogno della seguente dipendenza:

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

Utilizzate la strumentazione [OpenTelemetry Botocore a livello di codice per strumentare](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/botocore/botocore.html) tutti i client Boto3 della vostra applicazione. L'esempio seguente illustra `botocore` la strumentazione.

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

------

## Strumentazione delle chiamate HTTP in uscita tramite richieste
<a name="http-instrumentation-python"></a>

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

L'X-Ray Python SDK traccia le chiamate HTTP in uscita tramite le richieste applicando patch alla libreria delle richieste. Per ulteriori informazioni, consulta [Tracciare le chiamate ai servizi Web HTTP downstream utilizzando X-Ray SDK](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-python-httpclients.html) per Python. Nella tua applicazione, puoi utilizzare il `patch_all()` metodo per strumentare tutte le librerie o patchare selettivamente le librerie di richieste utilizzando. `patch((['requests']))` Qualsiasi opzione strumenta la `requests` libreria, generando un sottosegmento per ogni chiamata effettuata. `requests`

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

Per il seguente esempio di codice, è necessaria la seguente dipendenza:

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

 OpenTelemetry Utilizzate la strumentazione delle richieste a livello di codice per strumentare la libreria delle richieste per generare tracce per le richieste HTTP da essa effettuate nell'applicazione. [Per ulteriori informazioni, consulta request Instrumentation. OpenTelemetry ](https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/requests/requests.html) L'esempio seguente illustra la strumentazione della `requests` libreria.

```
from opentelemetry.instrumentation.requests import RequestsInstrumentor

# Instrument Requests
RequestsInstrumentor().instrument()

...

    example_session = requests.Session()
    example_session.get(url="https://example.com")
```

In alternativa, puoi anche strumentare la `urllib3` libreria sottostante per tracciare le richieste 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")
```

------

## Supporto strumentale per altre librerie
<a name="xray-migration-libraries-python"></a>

Puoi trovare l'elenco completo delle strumentazioni di libreria supportate per OpenTelemetry Python in [Librerie, framework, server](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/docs/supported-libraries.md) di applicazioni e. JVMs

In alternativa, puoi cercare OpenTelemetry nel Registro per scoprire se supporta la strumentazione. OpenTelemetry Consulta il [Registro](https://opentelemetry.io/ecosystem/registry/) per iniziare la ricerca.

## Creazione manuale di dati di traccia
<a name="manual-trace-creation-python"></a>

Puoi creare segmenti e sottosegmenti usando la nella `xray_recorder` tua applicazione Python. Per ulteriori informazioni, consulta [Strumentazione manuale del codice Python](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-python-middleware.html#xray-sdk-python-middleware-manual). Puoi anche aggiungere manualmente annotazioni e metadati ai dati di traccia.

**Creazione di intervalli con SDK OpenTelemetry **

Usa l'`start_as_current_span`API per avviare un intervallo e impostala per la creazione di intervalli. [Per esempi sulla creazione di intervalli, consulta Creazione di intervalli.](https://opentelemetry.io/docs/languages/python/instrumentation/#creating-spans) Una volta avviato un intervallo e rientrato nell'ambito corrente, è possibile aggiungervi ulteriori informazioni aggiungendo attributi, eventi, eccezioni, collegamenti e così via. Come abbiamo segmenti e sottosegmenti in X-Ray, ci sono diversi tipi di intervalli. OpenTelemetry Solo le campate `SERVER` tipo vengono convertite in segmenti a raggi X, mentre le altre vengono convertite in sottosegmenti a raggi X.

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

**Aggiungere annotazioni e metadati alle tracce con SDK OpenTelemetry **

L'X-Ray Python SDK fornisce informazioni separate APIs e consente di aggiungere annotazioni `put_annotation` e `put_metadata` metadati a una traccia. In OpenTelemetry SDK, le annotazioni e i metadati sono semplicemente attributi su un intervallo, aggiunti tramite l'API. `set_attribute`

Gli attributi Span che desideri siano annotazioni su una traccia vengono aggiunti sotto la chiave riservata il `aws.xray.annotations` cui valore è un elenco di coppie di annotazioni chiave-valore. Tutti gli altri attributi span diventano metadati sul segmento o sottosegmento convertito.

Inoltre, se si utilizza il collettore ADOT, è possibile configurare quali attributi span devono essere convertiti in annotazioni X-Ray specificando nella configurazione del collettore. `indexed_attributes`

L'esempio seguente mostra come aggiungere annotazioni e metadati a una traccia utilizzando SDK. OpenTelemetry 

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

## Strumentazione Lambda
<a name="lambda-instrumentation-python"></a>

Per monitorare le funzioni lambda su X-Ray, abiliti X-Ray e hai aggiunto le autorizzazioni appropriate al ruolo di invocazione della funzione. Inoltre, se stai tracciando le richieste downstream della tua funzione, dovresti strumentalizzare il codice con X-Ray Python SDK.

 OpenTelemetry Per X-Ray, si consiglia di utilizzare il AWS Lambda Layer per i segnali di [applicazione OpenTelemetry ](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-application-signals.html) disattivati. Questo strumenterà automaticamente la tua funzione e genererà intervalli per l'invocazione della funzione e qualsiasi richiesta derivante dalla tua funzione. Oltre al tracciamento, se sei interessato a utilizzare Application Signals per monitorare lo stato della tua funzione, consulta [Abilitare le tue applicazioni su Lambda](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Signals-Enable-LambdaMain.html).
+ Trova l'ARN del layer Lambda richiesto per la tua funzione da [AWS Lambda](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Signals-Enable-LambdaMain.html#Enable-Lambda-Layers) Layer for e aggiungilo. OpenTelemetry ARNs
+ Imposta le seguenti variabili di ambiente per la tua funzione.
  + `AWS_LAMBDA_EXEC_WRAPPER=/opt/otel-instrument`— Questo carica la strumentazione automatica per la funzione
  + `OTEL_AWS_APPLICATION_SIGNALS_ENABLED=false`— Ciò disabiliterà il monitoraggio dei segnali applicativi

**Creazione manuale di campate con la strumentazione Lambda**

Inoltre, puoi generare intervalli personalizzati all'interno della tua funzione per tenere traccia del lavoro. È possibile farlo utilizzando solo il `opentelemetry-api` pacchetto in combinazione con il AWS Lambda Layer OpenTelemetry per la strumentazione automatica.

1. Includili `opentelemetry-api` come dipendenza nella tua funzione

1. Il seguente frammento di codice è un esempio per generare intervalli personalizzati

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