@@ -277,6 +277,7 @@ def _handle_exception(
277
277
def __call__ (self , env , start_response ):
278
278
# pylint: disable=E1101
279
279
# pylint: disable=too-many-locals
280
+ # pylint: disable=too-many-branches
280
281
if self ._otel_excluded_urls .url_disabled (env .get ("PATH_INFO" , "/" )):
281
282
return super ().__call__ (env , start_response )
282
283
@@ -313,35 +314,38 @@ def __call__(self, env, start_response):
313
314
activation .__enter__ ()
314
315
env [_ENVIRON_SPAN_KEY ] = span
315
316
env [_ENVIRON_ACTIVATION_KEY ] = activation
317
+ exception = None
316
318
317
319
def _start_response (status , response_headers , * args , ** kwargs ):
318
320
response = start_response (
319
321
status , response_headers , * args , ** kwargs
320
322
)
321
- activation .__exit__ (None , None , None )
322
- if token is not None :
323
- context .detach (token )
324
323
return response
325
324
326
325
start = default_timer ()
327
326
try :
328
327
return super ().__call__ (env , _start_response )
329
328
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
337
330
raise
338
331
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 )
342
336
duration = max (round ((default_timer () - start ) * 1000 ), 0 )
343
337
self .duration_histogram .record (duration , duration_attrs )
344
338
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 )
345
349
346
350
347
351
class _TraceMiddleware :
0 commit comments