@@ -38,13 +38,39 @@ def my_lambda_handle(event, context):
38
38
"""
39
39
40
40
41
+ class _NoopDecorator (object ):
42
+
43
+ def __init__ (self , func ):
44
+ self .func = func
45
+
46
+ def __call__ (self , * args , ** kwargs ):
47
+ return self .func (* args , ** kwargs )
48
+
49
+
41
50
class _LambdaDecorator (object ):
42
51
"""
43
52
Decorator to automatically initialize Datadog API client, flush metrics,
44
53
and extracts/injects trace context.
45
54
"""
46
55
56
+ _instance = None
57
+ _force_new = False
58
+
59
+ def __new__ (cls , func ):
60
+ """
61
+ If the decorator is accidentally applied to multiple functions or
62
+ the same function multiple times, only the first one takes effect.
63
+
64
+ If _force_new, always return a real decorator, useful for unit tests.
65
+ """
66
+ if cls ._force_new or cls ._instance is None :
67
+ cls ._instance = super (_LambdaDecorator , cls ).__new__ (cls )
68
+ return cls ._instance
69
+ else :
70
+ return _NoopDecorator (func )
71
+
47
72
def __init__ (self , func ):
73
+ """Executes when the wrapped function gets wrapped"""
48
74
self .func = func
49
75
self .flush_to_log = os .environ .get ("DD_FLUSH_TO_LOG" , "" ).lower () == "true"
50
76
self .logs_injection = (
@@ -59,6 +85,17 @@ def __init__(self, func):
59
85
patch_all ()
60
86
logger .debug ("datadog_lambda_wrapper initialized" )
61
87
88
+ def __call__ (self , event , context , ** kwargs ):
89
+ """Executes when the wrapped function gets called"""
90
+ self ._before (event , context )
91
+ try :
92
+ return self .func (event , context , ** kwargs )
93
+ except Exception :
94
+ submit_errors_metric (context )
95
+ raise
96
+ finally :
97
+ self ._after (event , context )
98
+
62
99
def _before (self , event , context ):
63
100
set_cold_start ()
64
101
try :
@@ -78,15 +115,5 @@ def _after(self, event, context):
78
115
except Exception :
79
116
traceback .print_exc ()
80
117
81
- def __call__ (self , event , context , ** kwargs ):
82
- self ._before (event , context )
83
- try :
84
- return self .func (event , context , ** kwargs )
85
- except Exception :
86
- submit_errors_metric (context )
87
- raise
88
- finally :
89
- self ._after (event , context )
90
-
91
118
92
119
datadog_lambda_wrapper = _LambdaDecorator
0 commit comments