22# under the Apache License Version 2.0.
33# This product includes software developed at Datadog (https://www.datadoghq.com/).
44# Copyright 2019 Datadog, Inc.
5- import base64
65import os
76import logging
87import traceback
2322 XraySubsegment ,
2423 Headers ,
2524)
26- from datadog_lambda .metric import (
27- flush_stats ,
28- submit_invocations_metric ,
29- submit_errors_metric ,
30- )
3125from datadog_lambda .module_name import modify_module_name
3226from datadog_lambda .patch import patch_all
3327from datadog_lambda .span_pointers import calculate_span_pointers
@@ -248,7 +242,11 @@ def __call__(self, event, context, **kwargs):
248242 self .response = self .func (event , context , ** kwargs )
249243 return self .response
250244 except Exception :
251- submit_errors_metric (context )
245+ if not should_use_extension :
246+ from datadog_lambda .metric import submit_errors_metric
247+
248+ submit_errors_metric (context )
249+
252250 if self .span :
253251 self .span .set_traceback ()
254252 raise
@@ -274,6 +272,9 @@ def _inject_authorizer_span_headers(self, request_id):
274272 injected_headers [Headers .Parent_Span_Finish_Time ] = finish_time_ns
275273 if request_id is not None :
276274 injected_headers [Headers .Authorizing_Request_Id ] = request_id
275+
276+ import base64
277+
277278 datadog_data = base64 .b64encode (
278279 json .dumps (injected_headers , escape_forward_slashes = False ).encode ()
279280 ).decode ()
@@ -284,7 +285,12 @@ def _before(self, event, context):
284285 try :
285286 self .response = None
286287 set_cold_start (init_timestamp_ns )
287- submit_invocations_metric (context )
288+
289+ if not should_use_extension :
290+ from datadog_lambda .metric import submit_invocations_metric
291+
292+ submit_invocations_metric (context )
293+
288294 self .trigger_tags = extract_trigger_tags (event , context )
289295 # Extract Datadog trace context and source from incoming requests
290296 dd_context , trace_context_source , event_source = extract_dd_trace_context (
@@ -383,6 +389,8 @@ def _after(self, event, context):
383389 logger .debug ("Failed to create cold start spans. %s" , e )
384390
385391 if not self .flush_to_log or should_use_extension :
392+ from datadog_lambda .metric import flush_stats
393+
386394 flush_stats (context )
387395 if should_use_extension and self .local_testing_mode :
388396 # when testing locally, the extension does not know when an
0 commit comments