Skip to content

Commit 58d0e34

Browse files
authored
Catch errors when importing profiler. (#695)
* Catch errors when importing profiler. * Test import of profiler catches error and disables profiling. * Update linting.
1 parent 31df03d commit 58d0e34

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

datadog_lambda/wrapper.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@
4646
extract_http_status_code_tag,
4747
)
4848

49+
logger = logging.getLogger(__name__)
50+
4951
# ddtrace imports are also tested in
5052
# dd-trace-py/tests/internal/test_serverless.py please update those tests when
5153
# making changes to any ddtrace import.
@@ -61,8 +63,12 @@
6163

6264
start()
6365

66+
profiler = None
6467
if config.profiling_enabled:
65-
from ddtrace.profiling import profiler
68+
try:
69+
from ddtrace.profiling import profiler
70+
except Exception as e:
71+
logger.error(f"Failed to initialize profiler: [{e.__class__.__name__})] {e}")
6672

6773
if config.llmobs_enabled:
6874
from ddtrace.llmobs import LLMObs
@@ -75,8 +81,6 @@
7581
except ImportError:
7682
from ddtrace.debugging._uploader import LogsIntakeUploaderV1 as SignalUploader
7783

78-
logger = logging.getLogger(__name__)
79-
8084
DD_REQUESTS_SERVICE_NAME = "DD_REQUESTS_SERVICE_NAME"
8185
DD_SERVICE = "DD_SERVICE"
8286

@@ -141,7 +145,7 @@ def __init__(self, func):
141145
self.response = None
142146
self.blocking_response = None
143147

144-
if config.profiling_enabled:
148+
if config.profiling_enabled and profiler:
145149
self.prof = profiler.Profiler(env=config.env, service=config.service)
146150

147151
if config.trace_extractor:
@@ -283,7 +287,7 @@ def _before(self, event, context):
283287
self.blocking_response = get_asm_blocked_response(self.event_source)
284288
else:
285289
set_correlation_ids()
286-
if config.profiling_enabled and is_new_sandbox():
290+
if config.profiling_enabled and profiler and is_new_sandbox():
287291
self.prof.start(stop_on_exit=False, profile_children=True)
288292
logger.debug("datadog_lambda_wrapper _before() done")
289293
except Exception as e:

tests/test_wrapper.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -962,3 +962,13 @@ def lambda_handler(event, context):
962962
mock_submit.assert_called_once()
963963
call_args = mock_submit.call_args[0]
964964
assert call_args[0] is None
965+
966+
967+
@patch("datadog_lambda.config.Config.profiling_enabled", True)
968+
def test_profiling_import_errors_caught(monkeypatch):
969+
# when importing profiler fails, disable profiling instead of crashing app
970+
monkeypatch.setitem(
971+
sys.modules, "ddtrace.profiling", None
972+
) # force ModuleNotFoundError
973+
importlib.reload(wrapper)
974+
assert not hasattr(wrapper.datadog_lambda_wrapper, "prof")

0 commit comments

Comments
 (0)