Skip to content

Instantly share code, notes, and snippets.

@danilogco
Forked from philippegirard/main.py
Created May 2, 2022 22:51
Show Gist options
  • Save danilogco/4ee5afc7d4c801ad38ba0deaf7212898 to your computer and use it in GitHub Desktop.
Save danilogco/4ee5afc7d4c801ad38ba0deaf7212898 to your computer and use it in GitHub Desktop.
fastAPI sentry middleware
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