Registry / aws / aws-xray-sdk

aws-xray-sdk

JSON →
library2.15.0pypypi✓ verified 25d ago

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.

pip install aws-xray-sdk
INSTALL
IMPORT
SIG · AWS-XRAY-SDK
A
aws-xray-sdk
awspythonv2.15.0
Install
3.9s avg
Import
1191ms
Disk
50MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.15.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 1.262s · 51.1MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.9s · import 1.120s · 52MB
50MB installed
● package 50MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

xray_recorder
from aws_xray_sdk.core import xray_recorder
patch_all
from aws_xray_sdk.core import patch_all
Automatically patches supported libraries (e.g., boto3, requests, DB API 2.0 clients).
Segment
from aws_xray_sdk.core.segments import Segment
Used for manual segment creation, typically less common than using xray_recorder methods.
Subsegment
from aws_xray_sdk.core.segments import Subsegment
Used for manual subsegment creation.
SegmentNotFoundException
from aws_xray_sdk.core.exceptions.exceptions import SegmentNotFoundException
Common exception raised when attempting to interact with a non-existent segment/subsegment context.

This quickstart demonstrates how to configure the X-Ray recorder, patch supported libraries for automatic instrumentation, and use the `@xray_recorder.capture` decorator to create subsegments for function calls. It also shows manual segment creation for contexts not covered by middleware.

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.")
Debug
Known issues
breakingThe 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.
fix
Plan migration to AWS Distro for OpenTelemetry or OpenTelemetry Instrumentation before February 25, 2027.
affects: All versions (future updates will be limited to critical bug fixes and security updates).
breakingVersion 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.
fix
Upgrade your Python environment to 3.7 or newer. If stuck on older Python, you must use a 1.x version of the SDK, which is no longer actively maintained.
affects: 2.0.0 and higher
breakingVersion 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.
fix
Ensure `pynamodb` and `aiobotocore` versions support `botocore >= 1.11.3` when using `aws-xray-sdk` 2.x, or remain on `aws-xray-sdk` 1.x.
affects: 2.0.0 and higher
breakingThe `Subsegment.set_user()` API was removed in version 2.x as the corresponding attribute is not supported by the X-Ray backend.
fix
Remove any calls to `subsegment.set_user()` from your code. Consider using `put_annotation` or `put_metadata` if you need to associate user information, although direct user association may be better handled at the segment level if applicable.
affects: 2.0.0 and higher
gotchaContext 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.
fix
Carefully manage segment/subsegment context in multi-threaded applications using explicit `with xray_recorder.in_segment()` blocks or custom context passing. Consider if asynchronous patterns (like `asyncio` with appropriate instrumentation) or process-based parallelism might be better suited for X-Ray tracing.
affects: All 2.x versions
breakingThe script failed because the 'boto3' module was not found. 'boto3' is a common AWS SDK dependency for many Python applications interacting with AWS services.
fix
Ensure 'boto3' is included in your project's dependencies and is installed in the environment (e.g., via pip install boto3) where the script is executed.
affects: All versions (if boto3 is used without being installed)
breakingThe library `aws-xray-sdk` typically depends on `boto3` to interact with AWS services. If `boto3` is not installed in the environment, importing it will result in a `ModuleNotFoundError`.
fix
Ensure `boto3` is installed in your Python environment, for example, by adding `boto3` to your project's `requirements.txt` or installing it via `pip install boto3`.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'aws_xray_sdk'
The 'aws_xray_sdk' module is not included in the deployment package or is not installed in the environment.
fix
Ensure 'aws_xray_sdk' is installed in your environment using 'pip install aws-xray-sdk' and included in your deployment package.
ImportError: No module named 'jsonpickle'
The 'jsonpickle' module, a dependency of 'aws_xray_sdk', is missing from the environment.
fix
Install 'jsonpickle' using 'pip install jsonpickle' and include it in your deployment package.
AttributeError: 'NoneType' object has no attribute 'put_segment'
The X-Ray recorder is not properly initialized, leading to a 'NoneType' error when attempting to put a segment.
fix
Ensure the X-Ray recorder is correctly configured and initialized before use.
Runtime.ImportModuleError: Unable to import module 'lambda_function': No module named 'aws_xray_sdk'
The 'aws_xray_sdk' library is not included in the Lambda deployment package or an accessible Lambda layer for the Python function.
fix
Ensure the 'aws_xray_sdk' is installed and packaged with your Lambda deployment. For custom layers, include it in your zip file or specify 'aws-xray-sdk' in your `requirements.txt` if using tools that build layers. If using `aws-lambda-powertools`, ensure `aws-lambda-powertools[tracer]` is in your `requirements.txt` to include the X-Ray SDK.
cannot find the current segment/subsegment, please make sure you have a segment open
X-Ray SDK methods (such as `begin_subsegment`, `current_segment`, `put_annotation`) are called when there is no active X-Ray segment or subsegment in the current execution context, often in initialization code, background threads, or untraced sections of code.
fix
Ensure all X-Ray SDK operations are performed within an active segment or subsegment. For scenarios where a segment might not always be present (e.g., local testing or startup code), configure the recorder with `xray_recorder.configure(context_missing='LOG_ERROR')` to log warnings instead of raising exceptions. For new threads, ensure the X-Ray context is properly propagated.
Upgrade
Version history
2.15.0latest on PyPI · released Oct 29, 2025
Audit
Dependencies
botocorerequiredRequired for instrumenting AWS SDK clients.
wraptrequiredUsed for function wrapping and patching.
boto3optionalCommonly used with X-Ray for AWS service calls instrumentation.
DjangooptionalMiddleware for Django web framework integration.
FlaskoptionalMiddleware for Flask web framework integration.
requestsoptionalFor instrumenting HTTP client calls.
Agent activity
34 hits · last 30 days
node
28
OpenAI (training)
1
Resources