Add configurable request duration logging middleware #2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Add configurable request duration logging middleware
Summary
This PR adds a new configurable middleware to FastAPI that logs the duration of each HTTP request to a custom logger. The middleware provides flexible configuration options through Pydantic settings and follows FastAPI's existing middleware patterns.
Key Features:
time.perf_counter()
for high precisionFiles Added:
fastapi/middleware/requestlogging.py
- Main middleware implementationfastapi/middleware/settings.py
- Pydantic settings configurationtests/test_middleware_request_logging.py
- Complete test suitedocs_src/middleware/request_logging.py
- Usage documentation exampleFiles Modified:
fastapi/middleware/__init__.py
- Export new middlewareReview & Testing Checklist for Human
FASTAPI_REQUEST_LOGGING_ENABLED=false
,FASTAPI_REQUEST_LOGGING_LOGGER_NAME=custom.logger
, etc. work correctlyenabled=False
, no logging occurs and there's no performance overheadRecommended Test Plan:
Diagram
Notes
pydantic-settings
which I installed during development. This should be added to FastAPI's dependencies or made optional.time.perf_counter()
which is high-precision but adds a small overhead to every request. Consider making this opt-in for production environments.Link to Devin run: https://app.devin.ai/sessions/dbd89234593447b88a819c77c57825b7
Requested by: @the-coding-gopher