Debian Codegraph @

aws_xray_sdk/core/async_recorder.py

raw
1 import time
2 import traceback
3
4 import wrapt
5
6 from aws_xray_sdk.core.recorder import AWSXRayRecorder
7
8
9 class AsyncAWSXRayRecorder(AWSXRayRecorder):
10 def capture_async(self, name=None):
11 """
12 A decorator that records enclosed function in a subsegment.
13 It only works with asynchronous functions.
14
15 params str name: The name of the subsegment. If not specified
16 the function name will be used.
17 """
18
19 @wrapt.decorator
20 async def wrapper(wrapped, instance, args, kwargs):
21 func_name = name
22 if not func_name:
23 func_name = wrapped.__name__
24
25 result = await self.record_subsegment_async(
26 wrapped, instance, args, kwargs,
27 name=func_name,
28 namespace='local',
29 meta_processor=None,
30 )
31
32 return result
33
34 return wrapper
35
36 async def record_subsegment_async(self, wrapped, instance, args, kwargs, name,
37 namespace, meta_processor):
38
39 subsegment = self.begin_subsegment(name, namespace)
40
41 exception = None
42 stack = None
43 return_value = None
44
45 try:
46 return_value = await wrapped(*args, **kwargs)
47 return return_value
48 except Exception as e:
49 exception = e
50 stack = traceback.extract_stack(limit=self._max_trace_back)
51 raise
52 finally:
53 end_time = time.time()
54 if callable(meta_processor):
55 meta_processor(
56 wrapped=wrapped,
57 instance=instance,
58 args=args,
59 kwargs=kwargs,
60 return_value=return_value,
61 exception=exception,
62 subsegment=subsegment,
63 stack=stack,
64 )
65 elif exception:
66 if subsegment:
67 subsegment.add_exception(exception, stack)
68
69 self.end_subsegment(end_time)