Message Logger Middleware
Relevant source files
The following files were used as context for generating this wiki page:
The MessageLoggerMiddleware is a specialized ASGI middleware designed to provide granular visibility into the communication between the Uvicorn server and the ASGI application. It intercepts and logs every ASGI scope, receive event, and send event, facilitating low-level debugging of the protocol exchange.
This middleware operates by wrapping the application's receive and send callables, allowing it to record the exact data packets (messages) being passed back and forth. To keep logs readable and avoid flooding the output with binary data, it utilizes a placeholder system for large content fields like request bodies or WebSocket bytes.
Sources: uvicorn/middleware/message_logger.py:1-73, tests/middleware/test_message_logger.py:1-45
Core Architecture and Logic
The middleware implements the standard ASGI pattern, accepting an ASGI3Application during initialization and providing an async __call__ method for request handling.
Task Tracking and Context
Each request processed by the middleware is assigned a unique task_counter (incremented per instance). This counter allows developers to correlate multiple log entries (Started, Receive, Send, Completed) belonging to the same connection or lifecycle. It also attempts to extract the client's IP and port from the scope to provide a descriptive prefix for log entries.
Sources: uvicorn/middleware/message_logger.py:38-45
Data Flow and Interception
The middleware wraps the original ASGI components to log events as they occur:
- Scope Logging: The initial ASGI
scopeis logged immediately upon invocation. - Receive Interception: A nested
inner_receivefunction calls the originalreceivecallable, logs the resulting message with placeholders, and then returns it to the application. - Send Interception: A nested
inner_sendfunction logs the message provided by the application before passing it to the server's originalsendcallable.
The following sequence diagram illustrates how the middleware sits between the server protocol and the application:
The diagram shows the interception of the ASGI lifecycle, where the middleware acts as a transparent proxy that records data flow.
Sources: uvicorn/middleware/message_logger.py:47-73
Logging Mechanisms
Trace Level Logging
The middleware strictly uses the TRACE log level (integer value 5) for all its output. This ensures that detailed message logging does not interfere with standard DEBUG or INFO logs unless explicitly enabled by the user via the log_level="trace" configuration.
Sources: uvicorn/logging.py:11, uvicorn/middleware/message_logger.py:35-36
Message Placeholder Formatting
To prevent log bloat and protect sensitive binary data, the middleware uses the message_with_placeholders utility. This function creates a shallow copy of the ASGI message and replaces specific keys with descriptive strings indicating the size of the original content.
| Attribute | Placeholder Format | Description |
|---|---|---|
body | <{length} bytes> | Used for HTTP request/response bodies. |
bytes | <{length} bytes> | Used for WebSocket binary frames. |
text | <{length} chars> | Used for WebSocket text frames. |
headers | <...> | Ofuscates the header list to keep log lines concise. |
Sources: uvicorn/middleware/message_logger.py:14-31
Key Classes and Functions
MessageLoggerMiddleware
The primary class responsible for wrapping the application.
__init__(app): Initializes the middleware, sets thetask_counterto 0, and attaches a custom.trace()method to its logger for convenience.__call__(scope, receive, send): The entry point for each ASGI connection. It increments the counter, logs the scope, and executes the app with wrapped callables.
Sources: uvicorn/middleware/message_logger.py:33-45
message_with_placeholders(message)
A utility function used internally by the middleware.
- Input: A dictionary representing an ASGI
scopeormessage. - Logic: Iterates through the
PLACEHOLDER_FORMATkeys. If a key is present and contains data, it calculates the length and replaces the data with a formatted string. - Output: A new dictionary safe for logging at the TRACE level.
Sources: uvicorn/middleware/message_logger.py:14-31
Error Handling
The middleware includes a try...except...else block during the application execution.
- If the application raises an exception, the middleware logs
Raised exceptionat the TRACE level before re-raising the exception. - If the application completes successfully, it logs
Completed.
Sources: uvicorn/middleware/message_logger.py:65-73, tests/middleware/test_message_logger.py:28-45
Configuration Summary
The middleware relies on the standard Python logging module configured within Uvicorn.
| Configuration | Target Logger | Level Required |
|---|---|---|
| Log Level | uvicorn.asgi | TRACE (5) |
Sources: uvicorn/middleware/message_logger.py:36, tests/middleware/test_message_logger.py:16-17
The MessageLoggerMiddleware provides essential diagnostic information for developers working with custom ASGI protocols or debugging complex interaction patterns between the server and the application. By providing a clear, sequential record of every message exchanged, it simplifies the identification of protocol violations or data corruption issues.