Skip to content

Conversation

devin-ai-integration[bot]
Copy link

@devin-ai-integration devin-ai-integration bot commented Jun 28, 2025

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:

  • Measures request duration using time.perf_counter() for high precision
  • Configurable logger name, log level, and enable/disable functionality
  • Pydantic settings integration with environment variable support
  • Convenience function for easy setup
  • Comprehensive test coverage

Files Added:

  • fastapi/middleware/requestlogging.py - Main middleware implementation
  • fastapi/middleware/settings.py - Pydantic settings configuration
  • tests/test_middleware_request_logging.py - Complete test suite
  • docs_src/middleware/request_logging.py - Usage documentation example

Files Modified:

  • fastapi/middleware/__init__.py - Export new middleware

Review & Testing Checklist for Human

  • Test middleware functionality - Add the middleware to a FastAPI app and verify it logs request durations with correct format (method, path, status code, duration)
  • Verify environment variable configuration - Test that FASTAPI_REQUEST_LOGGING_ENABLED=false, FASTAPI_REQUEST_LOGGING_LOGGER_NAME=custom.logger, etc. work correctly
  • Test disable functionality - Ensure that when enabled=False, no logging occurs and there's no performance overhead
  • Check performance impact - Run load tests to ensure the middleware doesn't significantly impact request throughput
  • Test integration with existing apps - Add to an existing FastAPI application to ensure no conflicts with other middleware or logging configurations

Recommended Test Plan:

  1. Create a simple FastAPI app with the middleware enabled
  2. Make several requests and verify log output format
  3. Test with different log levels and custom logger names
  4. Test environment variable configuration
  5. Test with middleware disabled
  6. Test with multiple middleware layers to ensure proper ordering

Diagram

graph TD
    subgraph "FastAPI Core"
        App[FastAPI App] --> MW[Middleware Stack]
        MW --> Handler[Request Handlers]
    end
    
    subgraph "New Middleware Files"
        RL[fastapi/middleware/requestlogging.py]:::major-edit
        RS[fastapi/middleware/settings.py]:::major-edit
        Init[fastapi/middleware/__init__.py]:::minor-edit
    end
    
    subgraph "Test & Documentation"
        Tests[tests/test_middleware_request_logging.py]:::major-edit
        Docs[docs_src/middleware/request_logging.py]:::major-edit
    end
    
    subgraph "External Dependencies"
        PS[pydantic-settings]:::context
        Logging[Python logging]:::context
        Starlette[Starlette BaseHTTPMiddleware]:::context
    end
    
    App --> RL
    RL --> RS
    RL --> PS
    RL --> Logging
    RL --> Starlette
    Init --> RL
    
    subgraph Legend
        L1[Major Edit]:::major-edit
        L2[Minor Edit]:::minor-edit  
        L3[Context/No Edit]:::context
    end
    
    classDef major-edit fill:#90EE90
    classDef minor-edit fill:#87CEEB
    classDef context fill:#FFFFFF
Loading

Notes

  • Dependency: This feature requires pydantic-settings which I installed during development. This should be added to FastAPI's dependencies or made optional.
  • Performance: The middleware uses time.perf_counter() which is high-precision but adds a small overhead to every request. Consider making this opt-in for production environments.
  • Logging Integration: The middleware creates its own logger instance but integrates with Python's standard logging framework, so it should work with existing logging configurations.
  • Middleware Ordering: This middleware should typically be added early in the middleware stack to capture the full request duration including other middleware processing time.

Link to Devin run: https://app.devin.ai/sessions/dbd89234593447b88a819c77c57825b7
Requested by: @the-coding-gopher

- Create RequestLoggingMiddleware class using BaseHTTPMiddleware
- Implement duration measurement with time.perf_counter()
- Add RequestLoggingSettings with Pydantic for configuration
- Support enable/disable, custom logger name, and log level options
- Include convenience function add_request_logging_middleware()
- Add comprehensive tests covering all functionality
- Create documentation example showing usage patterns
- Follow FastAPI middleware patterns and integrate with existing infrastructure

Co-Authored-By: The Coding Gopher <thecodinggopher@gmail.com>
Copy link
Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants