77import logging
88import traceback
99
10- from datadog_lambda .metric import lambda_stats
10+ from datadog_lambda .metric import lambda_stats , lambda_metric
1111from datadog_lambda .patch import patch_all
12+ from datadog_lambda .tags import get_tags_from_context
1213from datadog_lambda .tracing import (
1314 extract_dd_trace_context ,
1415 set_correlation_ids ,
1516 inject_correlation_ids ,
1617)
1718
19+ ENHANCED_METRICS_NAMESPACE_PREFIX = "aws.lambda.enhanced"
20+
1821logger = logging .getLogger (__name__ )
1922
2023
@@ -31,6 +34,10 @@ def my_lambda_handle(event, context):
3134 requests.get("https://www.datadoghq.com")
3235"""
3336
37+ # On the first run of this Lambda container this variable is set
38+ # to the str value of the request ID, taken from the Lambda context
39+ cold_start_request_id = None
40+
3441
3542class _LambdaDecorator (object ):
3643 """
@@ -40,19 +47,29 @@ class _LambdaDecorator(object):
4047
4148 def __init__ (self , func ):
4249 self .func = func
43- self .flush_to_log = os .environ .get (' DD_FLUSH_TO_LOG' , '' ).lower () == ' true'
44- self .logs_injection = os .environ .get (' DD_LOGS_INJECTION' , '' ).lower () == ' true'
50+ self .flush_to_log = os .environ .get (" DD_FLUSH_TO_LOG" , "" ).lower () == " true"
51+ self .logs_injection = os .environ .get (" DD_LOGS_INJECTION" , "" ).lower () == " true"
4552
4653 # Inject trace correlation ids to logs
4754 if self .logs_injection :
4855 inject_correlation_ids ()
4956
5057 # Patch HTTP clients to propagate Datadog trace context
5158 patch_all ()
52- logger .debug (' datadog_lambda_wrapper initialized' )
59+ logger .debug (" datadog_lambda_wrapper initialized" )
5360
5461 def _before (self , event , context ):
62+ global cold_start_request_id
63+ # Assign this request ID as the cold start if there is no value yet
64+ if cold_start_request_id is None :
65+ cold_start_request_id = context .aws_request_id
66+
5567 try :
68+ lambda_metric (
69+ "{}.invocations" .format (ENHANCED_METRICS_NAMESPACE_PREFIX ),
70+ 1 ,
71+ tags = get_tags_from_context (context , cold_start_request_id ),
72+ )
5673 # Extract Datadog trace context from incoming requests
5774 extract_dd_trace_context (event )
5875
@@ -72,6 +89,13 @@ def __call__(self, event, context):
7289 self ._before (event , context )
7390 try :
7491 return self .func (event , context )
92+ except Exception :
93+ lambda_metric (
94+ "{}.errors" .format (ENHANCED_METRICS_NAMESPACE_PREFIX ),
95+ 1 ,
96+ tags = get_tags_from_context (context , cold_start_request_id ),
97+ )
98+ raise
7599 finally :
76100 self ._after (event , context )
77101
0 commit comments