Skip to content

Commit 8f203d0

Browse files
author
Emanuele Palazzetti
authored
[flask] avoid double instrumentation when TraceMiddleware is used (#538)
* [flask] refactor test suite and add missing test * [flask] safe-guard to avoid double instrumentation
1 parent 973fac4 commit 8f203d0

File tree

3 files changed

+201
-173
lines changed

3 files changed

+201
-173
lines changed

ddtrace/contrib/flask/middleware.py

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,22 @@ def __init__(self, app, tracer, service="flask", use_signals=True, distributed_t
2020
self.app = app
2121
log.debug('flask: initializing trace middleware')
2222

23-
self._tracer = tracer
24-
self._service = service
25-
self._use_distributed_tracing = distributed_tracing
23+
# Attach settings to the inner application middleware. This is required if double
24+
# instrumentation happens (i.e. `ddtrace-run` with `TraceMiddleware`). In that
25+
# case, `ddtrace-run` instruments the application, but then users code is unable
26+
# to update settings such as `distributed_tracing` flag. This step can be removed
27+
# when the `Config` object is used
28+
self.app._tracer = tracer
29+
self.app._service = service
30+
self.app._use_distributed_tracing = distributed_tracing
2631
self.use_signals = use_signals
2732

28-
self._tracer.set_service_info(
33+
# safe-guard to avoid double instrumentation
34+
if getattr(app, '__dd_instrumentation', False):
35+
return
36+
setattr(app, '__dd_instrumentation', True)
37+
38+
self.app._tracer.set_service_info(
2939
service=service,
3040
app="flask",
3141
app_type=AppTypes.web,
@@ -97,16 +107,16 @@ def _teardown_request(self, exception):
97107
log.debug('flask: error finishing span', exc_info=True)
98108

99109
def _start_span(self):
100-
if self._use_distributed_tracing:
110+
if self.app._use_distributed_tracing:
101111
propagator = HTTPPropagator()
102112
context = propagator.extract(request.headers)
103113
# Only need to active the new context if something was propagated
104114
if context.trace_id:
105-
self._tracer.context_provider.activate(context)
115+
self.app._tracer.context_provider.activate(context)
106116
try:
107-
g.flask_datadog_span = self._tracer.trace(
117+
g.flask_datadog_span = self.app._tracer.trace(
108118
SPAN_NAME,
109-
service=self._service,
119+
service=self.app._service,
110120
span_type=http.TYPE,
111121
)
112122
except Exception:

0 commit comments

Comments
 (0)