AWS SDK Extension for OpenTelemetry

2.1.0 · active · verified Thu Apr 09

The opentelemetry-sdk-extension-aws library, currently at version 2.1.0, provides components to configure the OpenTelemetry SDK for Python, primarily enabling compatibility with AWS X-Ray tracing. It offers custom ID generators for X-Ray compatible trace IDs and AWS resource detectors to automatically enrich telemetry data with AWS-specific metadata. The project is actively maintained as part of the wider opentelemetry-python-contrib monorepo and follows its release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure the OpenTelemetry Python SDK using `opentelemetry-sdk-extension-aws`. It initializes a `TracerProvider` with `AwsXRayIdGenerator` to ensure trace ID compatibility with AWS X-Ray and includes an `Ec2ResourceDetector` to automatically add AWS EC2 metadata to your traces. Spans are then exported to the console.

import os
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.sdk.extension.aws.trace import AwsXRayIdGenerator
from opentelemetry.sdk.extension.aws.resource.ec2 import Ec2ResourceDetector

# 1. Configure the TracerProvider with the X-Ray ID Generator for trace ID compatibility
# This is crucial for traces to be accepted and correlated correctly by AWS X-Ray.
tracer_provider = TracerProvider(id_generator=AwsXRayIdGenerator())
trace.set_tracer_provider(tracer_provider)

# 2. Detect AWS specific resource attributes (e.g., EC2 instance metadata)
# For a local runnable example, we use a basic resource and merge with detected EC2 attributes.
# In an actual EC2 environment, Ec2ResourceDetector.detect() would populate real metadata.
resource = Resource.create({"service.name": os.environ.get("OTEL_SERVICE_NAME", "my-aws-app")})
# Attempt to detect EC2 resources; if not on EC2, this will yield an empty resource.
# The merge operation combines the service name with any detected AWS resource attributes.
tracer_provider.resource = resource.merge(Ec2ResourceDetector().detect())

# 3. Configure a simple span processor and console exporter for demonstration
span_processor = SimpleSpanProcessor(ConsoleSpanExporter())
tracer_provider.add_span_processor(span_processor)

# 4. Get a tracer and create some spans
tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span("my-aws-operation"):
    print("Performing an operation traced with OpenTelemetry and AWS X-Ray compatible IDs.")
    with tracer.start_as_current_span("sub-operation"):
        print("This is a sub-operation within the main task.")

print("OpenTelemetry with AWS X-Ray compatibility and resource detection configured.")
print("Check console output for example spans.")

view raw JSON →