Created
April 19, 2020 00:55
-
-
Save philippegirard/920f1ff2990beb0f7b7ead07c68a32db to your computer and use it in GitHub Desktop.
fastAPI sentry middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sentry_sdk | |
from fastapi import FastAPI | |
sentry_sdk.init( | |
dsn="your_dns", | |
) | |
app = FastAPI() | |
@app.middleware("http") | |
async def sentry_exception(request: Request, call_next): | |
try: | |
response = await call_next(request) | |
return response | |
except Exception as e: | |
with sentry_sdk.push_scope() as scope: | |
scope.set_context("request", request) | |
user_id = "database_user_id" # when available | |
scope.user = { | |
"ip_address": request.client.host, | |
"id": user_id | |
} | |
sentry_sdk.capture_exception(e) | |
raise e | |
@app.get("/") | |
async def root(): | |
return {"status": "alive"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment