1
1
import json
2
2
3
+ import requests
4
+
3
5
from aws_lambda_powertools .logging import logger_inject_lambda_context , logger_setup
4
- from aws_lambda_powertools .tracing import Tracer
5
6
from aws_lambda_powertools .metrics import Metrics , MetricUnit , single_metric
6
- import requests
7
+ from aws_lambda_powertools .middleware_factory import lambda_handler_decorator
8
+ from aws_lambda_powertools .tracing import Tracer
7
9
8
10
tracer = Tracer ()
9
11
logger = logger_setup ()
13
15
14
16
metrics .add_dimension (name = "operation" , value = "example" )
15
17
18
+
19
+ @lambda_handler_decorator (trace_execution = True )
20
+ def my_middleware (handler , event , context , say_hello = False ):
21
+ if say_hello :
22
+ print ("========= HELLO PARAM DETECTED =========" )
23
+ print ("========= Logging event before Handler is called =========" )
24
+ print (event )
25
+ ret = handler (event , context )
26
+ print ("========= Logging response after Handler is called =========" )
27
+ print (ret )
28
+ return ret
29
+
30
+
16
31
@metrics .log_metrics
17
32
@tracer .capture_lambda_handler
33
+ @my_middleware (say_hello = True )
18
34
@logger_inject_lambda_context
19
35
def lambda_handler (event , context ):
20
36
"""Sample pure Lambda function
@@ -41,25 +57,22 @@ def lambda_handler(event, context):
41
57
if _cold_start :
42
58
logger .debug ("Recording cold start metric" )
43
59
metrics .add_metric (name = "ColdStart" , unit = MetricUnit .Count , value = 1 )
44
- metrics .add_dimension (name = "function_name" , value = context .function_name )
60
+ metrics .add_dimension (name = "function_name" , value = context .function_name )
45
61
_cold_start = False
46
62
47
63
try :
48
64
ip = requests .get ("http://checkip.amazonaws.com/" )
49
65
metrics .add_metric (name = "SuccessfulLocations" , unit = "Count" , value = 1 )
50
66
except requests .RequestException as e :
51
67
# Send some context about this error to Lambda Logs
52
- logger .error ( e )
53
- raise e
54
-
68
+ logger .exception ( e , exc_info = True )
69
+ raise
70
+
55
71
with single_metric (name = "UniqueMetricDimension" , unit = "Seconds" , value = 1 ) as metric :
56
72
metric .add_dimension (name = "unique_dimension" , value = "for_unique_metric" )
57
73
58
74
logger .info ("Returning message to the caller" )
59
75
return {
60
76
"statusCode" : 200 ,
61
- "body" : json .dumps ({
62
- "message" : "hello world" ,
63
- "location" : ip .text .replace ("\n " , "" )
64
- }),
77
+ "body" : json .dumps ({"message" : "hello world" , "location" : ip .text .replace ("\n " , "" )}),
65
78
}
0 commit comments