@@ -277,6 +277,7 @@ def _handle_exception(
277277 def __call__ (self , env , start_response ):
278278 # pylint: disable=E1101
279279 # pylint: disable=too-many-locals
280+ # pylint: disable=too-many-branches
280281 if self ._otel_excluded_urls .url_disabled (env .get ("PATH_INFO" , "/" )):
281282 return super ().__call__ (env , start_response )
282283
@@ -313,35 +314,38 @@ def __call__(self, env, start_response):
313314 activation .__enter__ ()
314315 env [_ENVIRON_SPAN_KEY ] = span
315316 env [_ENVIRON_ACTIVATION_KEY ] = activation
317+ exception = None
316318
317319 def _start_response (status , response_headers , * args , ** kwargs ):
318320 response = start_response (
319321 status , response_headers , * args , ** kwargs
320322 )
321- activation .__exit__ (None , None , None )
322- if token is not None :
323- context .detach (token )
324323 return response
325324
326325 start = default_timer ()
327326 try :
328327 return super ().__call__ (env , _start_response )
329328 except Exception as exc :
330- activation .__exit__ (
331- type (exc ),
332- exc ,
333- getattr (exc , "__traceback__" , None ),
334- )
335- if token is not None :
336- context .detach (token )
329+ exception = exc
337330 raise
338331 finally :
339- duration_attrs [
340- SpanAttributes .HTTP_STATUS_CODE
341- ] = span .attributes .get (SpanAttributes .HTTP_STATUS_CODE )
332+ if span .is_recording ():
333+ duration_attrs [
334+ SpanAttributes .HTTP_STATUS_CODE
335+ ] = span .attributes .get (SpanAttributes .HTTP_STATUS_CODE )
342336 duration = max (round ((default_timer () - start ) * 1000 ), 0 )
343337 self .duration_histogram .record (duration , duration_attrs )
344338 self .active_requests_counter .add (- 1 , active_requests_count_attrs )
339+ if exception is None :
340+ activation .__exit__ (None , None , None )
341+ else :
342+ activation .__exit__ (
343+ type (exception ),
344+ exception ,
345+ getattr (exception , "__traceback__" , None ),
346+ )
347+ if token is not None :
348+ context .detach (token )
345349
346350
347351class _TraceMiddleware :
0 commit comments