AWS X-Ray SDK for Python
The AWS X-Ray SDK for Python (the SDK) enables Python developers to record and emit information from within their applications to the AWS X-Ray service. The library is currently at version 2.15.0 and receives regular updates, though it will enter maintenance mode on February 25, 2026, with end-of-support on February 25, 2027, with a recommendation to migrate to OpenTelemetry.
Warnings
- breaking The AWS X-Ray SDKs will enter maintenance mode on February 25, 2026, and reach end-of-support on February 25, 2027. AWS recommends migrating to AWS Distro for OpenTelemetry (ADOT) or OpenTelemetry Instrumentation for future tracing needs.
- breaking Version 2.x of the SDK dropped support for Python 2.7 and Python 3.4. All versions 2.x and higher require Python >= 3.7.
- breaking Version 2.x introduced an incompatibility with `pynamodb` and `aiobotocore` if those libraries require `botocore < 1.11.3`. Ensure these dependencies are compatible with newer `botocore` versions if upgrading to `aws-xray-sdk` 2.x.
- breaking The `Subsegment.set_user()` API was removed in version 2.x as the corresponding attribute is not supported by the X-Ray backend.
- gotcha Context propagation for traces and subsegments across threads (non-asyncio) can be tricky and may not work as expected, potentially leading to `SegmentNotFoundException` or incomplete traces. The Python SDK doesn't explicitly detail multi-threading context management as clearly as other language SDKs.
Install
-
pip install aws-xray-sdk
Imports
- xray_recorder
from aws_xray_sdk.core import xray_recorder
- patch_all
from aws_xray_sdk.core import patch_all
- Segment
from aws_xray_sdk.core.segments import Segment
- Subsegment
from aws_xray_sdk.core.segments import Subsegment
- SegmentNotFoundException
from aws_xray_sdk.core.exceptions.exceptions import SegmentNotFoundException
Quickstart
import os
from aws_xray_sdk.core import xray_recorder, patch_all
import boto3
# Configure the X-Ray recorder globally
# For local development without a daemon, set sampling=False to prevent errors
# In deployed AWS environments, the daemon address is often discovered automatically.
xray_recorder.configure(
service='MyPythonApp',
sampling=False, # Set to True or rely on daemon for actual sampling rules in production
context_missing='LOG_ERROR', # Other options: 'RUNTIME_ERROR', 'IGNORE'
daemon_address=os.environ.get('AWS_XRAY_DAEMON_ADDRESS', '127.0.0.1:2000')
)
# Patch supported libraries to automatically instrument calls (e.g., boto3)
patch_all()
# Example: Instrumenting an AWS SDK call with a decorator
@xray_recorder.capture('s3_list_buckets')
def list_s3_buckets():
# Ensure AWS credentials/config are set in environment or ~/.aws/config
s3_client = boto3.client('s3', region_name='us-east-1')
try:
response = s3_client.list_buckets()
bucket_names = [bucket['Name'] for bucket in response.get('Buckets', [])]
# Add custom metadata to the current subsegment
xray_recorder.current_subsegment().put_metadata('bucket_count', len(bucket_names))
return bucket_names
except Exception as e:
# Record exceptions to the current subsegment
xray_recorder.current_subsegment().add_exception(e)
raise
# Manual segment creation (if not using web framework middleware or a top-level decorator)
# This mimics an incoming request context.
with xray_recorder.in_segment(xray_recorder.begin_segment('MyApplicationRootTrace')):
print("Starting application trace...")
try:
buckets = list_s3_buckets()
print(f"Successfully listed {len(buckets)} S3 buckets.")
# Add an annotation to the root segment
xray_recorder.current_segment().put_annotation('result', 'success')
except Exception as e:
print(f"An error occurred: {e}")
xray_recorder.current_segment().put_annotation('result', 'failure')
xray_recorder.current_segment().add_exception(e)
print("Trace completed.")