Skip to content

Commit f672621

Browse files
committed
Certain xray_recorder operations only work in the LambdaContext
1 parent 5e37689 commit f672621

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

datadog_lambda/tracing.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import logging
77

88
from aws_xray_sdk.core import xray_recorder
9+
from aws_xray_sdk.core.lambda_launcher import LambdaContext
910

1011
from ddtrace import patch, tracer
1112
from datadog_lambda.constants import (
@@ -94,6 +95,10 @@ def get_dd_trace_context():
9495
automatically, but this function can be used to manually inject the trace
9596
context to an outgoing request.
9697
"""
98+
if not is_lambda_context():
99+
logger.debug('get_dd_trace_context is only supported in LambdaContext')
100+
return {}
101+
97102
global dd_trace_context
98103
xray_trace_entity = xray_recorder.get_trace_entity() # xray (sub)segment
99104
if dd_trace_context:
@@ -124,7 +129,12 @@ def set_correlation_ids():
124129
125130
TODO: Remove me when Datadog tracer is natively supported in Lambda.
126131
"""
132+
if not is_lambda_context():
133+
logger.debug('set_correlation_ids is only supported in LambdaContext')
134+
return
135+
127136
context = get_dd_trace_context()
137+
128138
span = tracer.trace('dummy.span')
129139
span.trace_id = context[TraceHeader.TRACE_ID]
130140
span.span_id = context[TraceHeader.PARENT_ID]
@@ -154,3 +164,11 @@ def inject_correlation_ids():
154164
patch(logging=True)
155165

156166
logger.debug('logs injection configured')
167+
168+
169+
def is_lambda_context():
170+
"""
171+
Return True if the X-Ray context is `LambdaContext`, rather than the
172+
regular `Context` (e.g., when testing lambda functions locally).
173+
"""
174+
return type(xray_recorder.context) == LambdaContext

tests/test_tracing.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ def setUp(self):
3535
self.mock_current_subsegment
3636
self.addCleanup(patcher.stop)
3737

38+
patcher = patch('datadog_lambda.tracing.is_lambda_context')
39+
self.mock_is_lambda_context = patcher.start()
40+
self.mock_is_lambda_context.return_value = True
41+
self.addCleanup(patcher.stop)
42+
3843
def test_without_datadog_trace_headers(self):
3944
extract_dd_trace_context({})
4045
self.assertDictEqual(
@@ -165,6 +170,11 @@ def setUp(self):
165170
}
166171
self.addCleanup(patcher.stop)
167172

173+
patcher = patch('datadog_lambda.tracing.is_lambda_context')
174+
self.mock_is_lambda_context = patcher.start()
175+
self.mock_is_lambda_context.return_value = True
176+
self.addCleanup(patcher.stop)
177+
168178
def test_set_correlation_ids(self):
169179
set_correlation_ids()
170180
trace_id, span_id = get_correlation_ids()

0 commit comments

Comments
 (0)