-
-
Save danilogco/4ee5afc7d4c801ad38ba0deaf7212898 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