1
- # AWS X-Ray SDK for Python < sup >< sup >< sup >(beta)</ sup ></ sup ></ sup >
1
+ # AWS X-Ray SDK for Python
2
2
3
3
![ Screenshot of the AWS X-Ray console] ( /images/example_servicemap.png?raw=true )
4
4
@@ -104,6 +104,31 @@ async def main():
104
104
await myfunc()
105
105
```
106
106
107
+ ### Adding annotations/metadata using recorder
108
+
109
+ ``` python
110
+ from aws_xray_sdk.core import xray_recorder
111
+
112
+ # Start a segment if no segment exist
113
+ segment1 = xray_recorder.begin_segment(' segment_name' )
114
+
115
+ # This will add the key value pair to segment1 as it is active
116
+ xray_recorder.put_annotation(' key' , ' value' )
117
+
118
+ # Start a subsegment so it becomes the active trace entity
119
+ subsegment1 = xray_recorder.begin_subsegment(' subsegment_name' )
120
+
121
+ # This will add the key value pair to subsegment1 as it is active
122
+ xray_recorder.put_metadata(' key' , ' value' )
123
+
124
+ if xray_recorder.is_sampled():
125
+ # some expensitve annotations/metadata generation code here
126
+ val = compute_annotation_val()
127
+ metadata = compute_metadata_body()
128
+ xray_recorder.put_annotation(' mykey' , val)
129
+ xray_recorder.put_metadata(' mykey' , metadata)
130
+ ```
131
+
107
132
### Trace AWS Lambda functions
108
133
109
134
``` python
@@ -123,6 +148,47 @@ def lambda_handler(event, context):
123
148
# ... some other code
124
149
```
125
150
151
+ ### Trace ThreadPoolExecutor
152
+
153
+ ``` python
154
+ import concurrent.futures
155
+
156
+ import requests
157
+
158
+ from aws_xray_sdk.core import xray_recorder
159
+ from aws_xray_sdk.core import patch
160
+
161
+ patch((' requests' ,))
162
+
163
+ URLS = [' http://www.amazon.com/' ,
164
+ ' http://aws.amazon.com/' ,
165
+ ' http://example.com/' ,
166
+ ' http://www.bilibili.com/' ,
167
+ ' http://invalid-domain.com/' ]
168
+
169
+ def load_url (url , trace_entity ):
170
+ # Set the parent X-Ray entity for the worker thread.
171
+ xray_recorder.set_trace_entity(trace_entity)
172
+ # Subsegment captured from the following HTTP GET will be
173
+ # a child of parent entity passed from the main thread.
174
+ resp = requests.get(url)
175
+ # prevent thread pollution
176
+ xray_recorder.clear_trace_entities()
177
+ return resp
178
+
179
+ # Get the current active segment or subsegment from the main thread.
180
+ current_entity = xray_recorder.get_trace_entity()
181
+ with concurrent.futures.ThreadPoolExecutor(max_workers = 5 ) as executor:
182
+ # Pass the active entity from main thread to worker threads.
183
+ future_to_url = {executor.submit(load_url, url, current_entity): url for url in URLS }
184
+ for future in concurrent.futures.as_completed(future_to_url):
185
+ url = future_to_url[future]
186
+ try :
187
+ data = future.result()
188
+ except Exception :
189
+ pass
190
+ ```
191
+
126
192
### Patch third-party libraries
127
193
128
194
``` python
0 commit comments