Save the request_id in the Request state

This commit is contained in:
Santiago Lo Coco 2023-11-10 17:39:55 -03:00
parent f858853a22
commit a860af0ff9
3 changed files with 17 additions and 1 deletions

View File

@ -41,6 +41,20 @@ app.add_middleware(
)
```
### Accessing request ID in the called function
The `execute_request` method has been updated to set the `request_id` in the `request.state`. You can now access it in the called function using `request.state.request_id`. Here is an example:
```python
# ...
@app.get("/example")
async def example_route(request: Request):
# Accessing the request_id in the called function
request_id = request.state.request_id
return {"message": "Hello, world!", "request_id": request_id}
```
## Configuration
The library relies on a logging configuration dictionary (`logging_config`) to set up JSON logging. Because of that, it includes a default logging configuration (`logging_config`), which you can import for easy setup. Ensure this configuration is properly set before adding the middleware to your FastAPI app.

View File

@ -121,6 +121,7 @@ class RouterLoggingMiddleware(BaseHTTPMiddleware):
self, call_next: Callable, request: Request, request_id: str
) -> Response:
try:
request.state.request_id = request_id
response: Response = await call_next(request)
response.headers["X-API-Request-ID"] = request_id

View File

@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "logmiddleware"
version = "0.0.1"
version = "0.0.3"
description = "Simplify the logging of incoming requests and outgoing responses."
readme = "README.md"
requires-python = ">=3.8"
@ -33,6 +33,7 @@ classifiers = [
]
dependencies = [
"fastapi>=0.103.2",
"python-json-logger>=2.0.7"
]
[project.urls]