-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathlogging.py
More file actions
40 lines (33 loc) · 1.74 KB
/
logging.py
File metadata and controls
40 lines (33 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"""
If a structlog contextvar approach is used, it's possible for context to be lost since fastapi/starlette
can run threaded, forked, and async code. I don't claim to fully understand exactly *why* starlette-context
is needed, and it's possible that it's not needed at all at this point.
References:
- https://pypi.org/project/fastapi-structlog/0.5.0/ (https://github.com/iloveitaly/fastapi-logger)
- https://pypi.org/project/asgi-correlation-id/ - used to generate a request ID that is added to all logs
- https://gist.github.com/nymous/f138c7f06062b7c43c060bf03759c29e
- https://github.com/sharu1204/fastapi-structlog/blob/master/app/main.py - old implementation
- https://github.com/tomwojcik/starlette-context
"""
import sentry_sdk
from fastapi import FastAPI
from starlette.middleware.base import RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response
from starlette_context import context, plugins
from starlette_context.header_keys import HeaderKeys
from starlette_context.middleware import RawContextMiddleware
def add_middleware(app: FastAPI):
@app.middleware("http")
async def sentry_transaction_id_middleware(
request: Request, call_next: RequestResponseEndpoint
) -> Response:
# https://github.com/snok/asgi-correlation-id/blob/ed006dcc119447bf68a170bd1557f6015427213d/asgi_correlation_id/extensions/sentry.py#L18-L33
# https://blog.sentry.io/trace-errors-through-stack-using-unique-identifiers-in-sentry/
scope = sentry_sdk.get_isolation_scope()
scope.set_tag("transaction_id", context[HeaderKeys.request_id])
return await call_next(request)
app.add_middleware(
RawContextMiddleware,
plugins=(plugins.RequestIdPlugin(),),
)