Skip to content

Commit 2609f53

Browse files
author
Peter Giacomo Lombardo
authored
FastAPI: Capture exception detail on 5xx (#286)
* FastAPI: Capture exception detail on 5xx * Version limit urllib3 to sidestep bug The following seems to be occurring with 1.26.0: > ImportError: cannot import name 'HTTPHeaderDict' from 'urllib3.connection'
1 parent cde140d commit 2609f53

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

instana/instrumentation/fastapi_inst.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,31 @@
1313
from ..util import running_in_gunicorn
1414
from .asgi import InstanaASGIMiddleware
1515
from starlette.middleware import Middleware
16+
from fastapi import HTTPException
17+
from fastapi.exception_handlers import http_exception_handler
18+
19+
from instana.singletons import async_tracer
1620

1721
if hasattr(fastapi, '__version__') and \
1822
(LooseVersion(fastapi.__version__) >= LooseVersion('0.51.0')):
1923

24+
async def instana_exception_handler(request, exc):
25+
"""
26+
We capture FastAPI HTTPException, log the error and pass it on
27+
to the default exception handler.
28+
"""
29+
try:
30+
span = async_tracer.active_span
31+
32+
if span is not None:
33+
if hasattr(exc, 'detail'):
34+
span.set_tag('http.error', exc.detail)
35+
span.set_tag('http.status_code', exc.status_code)
36+
except Exception:
37+
logger.debug("FastAPI instana_exception_handler: ", exc_info=True)
38+
39+
return await http_exception_handler(request, exc)
40+
2041
@wrapt.patch_function_wrapper('fastapi.applications', 'FastAPI.__init__')
2142
def init_with_instana(wrapped, instance, args, kwargs):
2243
middleware = kwargs.get('middleware')
@@ -25,6 +46,13 @@ def init_with_instana(wrapped, instance, args, kwargs):
2546
elif isinstance(middleware, list):
2647
middleware.append(Middleware(InstanaASGIMiddleware))
2748

49+
exception_handlers = kwargs.get('exception_handlers')
50+
if exception_handlers is None:
51+
kwargs['exception_handlers'] = dict()
52+
53+
if isinstance(kwargs['exception_handlers'], dict):
54+
kwargs['exception_handlers'][HTTPException] = instana_exception_handler
55+
2856
return wrapped(*args, **kwargs)
2957

3058
logger.debug("Instrumenting FastAPI")

setup.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,14 +79,14 @@ def check_setuptools():
7979
'nose>=1.0',
8080
'pyramid>=1.2',
8181
'pytest>=4.6',
82-
'urllib3[secure]>=1.15'
82+
'urllib3[secure]>=1.15,<=1.25.11'
8383
],
8484
'test-cassandra': [
8585
'cassandra-driver==3.20.2',
8686
'mock>=2.0.0',
8787
'nose>=1.0',
8888
'pytest>=4.6',
89-
'urllib3[secure]>=1.15'
89+
'urllib3[secure]>=1.15<=1.25.11'
9090
],
9191
'test-couchbase': [
9292
'couchbase==2.5.9',
@@ -122,7 +122,7 @@ def check_setuptools():
122122
'suds-jurko>=0.6',
123123
'tornado>=4.5.3,<6.0',
124124
'uvicorn>=0.12.2;python_version>="3.6"',
125-
'urllib3[secure]>=1.15'
125+
'urllib3[secure]>=1.15,<=1.25.11'
126126
],
127127
},
128128
test_suite='nose.collector',

0 commit comments

Comments
 (0)