From a860af0ff9aa7cb0f93e7739c844a86cea04ed9a Mon Sep 17 00:00:00 2001 From: Santiago Lo Coco Date: Fri, 10 Nov 2023 17:39:55 -0300 Subject: [PATCH] Save the request_id in the Request state --- README.md | 14 ++++++++++++++ logmiddleware/middleware.py | 1 + pyproject.toml | 3 ++- 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e52b3fa..7261170 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/logmiddleware/middleware.py b/logmiddleware/middleware.py index 1e95287..df64f8e 100644 --- a/logmiddleware/middleware.py +++ b/logmiddleware/middleware.py @@ -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 diff --git a/pyproject.toml b/pyproject.toml index 51f885a..da95cd7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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]