Skip to content

Commit ebfe096

Browse files
committed
move activation closer to __call__ as well
1 parent 1ad6b49 commit ebfe096

File tree

1 file changed

+21
-18
lines changed
  • instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware

1 file changed

+21
-18
lines changed

instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware/otel_middleware.py

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,17 @@ def __call__(self, request):
162162
response = self.get_response(request)
163163
return self.process_response(request, response)
164164
finally:
165+
# record any exceptions raised while processing the request
166+
exception = request.META.pop(self._environ_exception_key, None)
167+
168+
if exception:
169+
activation.__exit__(
170+
type(exception),
171+
exception,
172+
getattr(exception, "__traceback__", None),
173+
)
174+
else:
175+
activation.__exit__(None, None, None)
165176

166177
if request.META.get(self._environ_token, None) is not None:
167178
detach(request.META.get(self._environ_token))
@@ -179,6 +190,15 @@ def _run_request_hook(self, request):
179190
# would not be called. Log the exception instead.
180191
_logger.exception("Exception raised by request_hook")
181192

193+
def _run_response_hook(self, span, request, response):
194+
if _DjangoMiddleware._otel_response_hook:
195+
try:
196+
_DjangoMiddleware._otel_response_hook( # pylint: disable=not-callable
197+
span, request, response
198+
)
199+
except Exception: # pylint: disable=broad-exception-caught
200+
_logger.exception("Exception raised by response_hook")
201+
182202
@staticmethod
183203
def _get_span_name(request):
184204
method = sanitize_method(request.method.strip())
@@ -398,25 +418,8 @@ def process_response(self, request, response):
398418
if propagator:
399419
propagator.inject(response)
400420

401-
# record any exceptions raised while processing the request
402-
exception = request.META.pop(self._environ_exception_key, None)
421+
self._run_response_hook(span, request, response)
403422

404-
if _DjangoMiddleware._otel_response_hook:
405-
try:
406-
_DjangoMiddleware._otel_response_hook( # pylint: disable=not-callable
407-
span, request, response
408-
)
409-
except Exception: # pylint: disable=broad-exception-caught
410-
_logger.exception("Exception raised by response_hook")
411-
412-
if exception:
413-
activation.__exit__(
414-
type(exception),
415-
exception,
416-
getattr(exception, "__traceback__", None),
417-
)
418-
else:
419-
activation.__exit__(None, None, None)
420423

421424
if request_start_time is not None:
422425
duration_s = default_timer() - request_start_time

0 commit comments

Comments
 (0)