Introducing a new way to review your PRs.

Read the announcement

aio-libs / aiohttp

Asynchronous HTTP client/server framework for asyncio and Python

View on GitHub

19 documents · Updated Nov 23, 2026

docs / observability-and-test-support

Observability and test support

aiohttp provides shared ways to observe server and client activity and to test both sides without building a full deployment for every case. Server access logs describe completed requests, client tracing exposes timed request stages through callbacks, and test utilities provide either realistic local servers or focused request fixtures.

Observability surfaces

The observability surfaces split by the direction of traffic. Server logging records the result of an incoming request, while client tracing lets an application watch the steps that lead to an outgoing request.

SurfaceMain useIntegration point
Server loggerRecord server events and errorsNamed loggers and request-handler logging
Access loggerRecord one access entry after response handlingAbstractAccessLogger or AbstractAsyncAccessLogger
Client tracingMeasure or correlate outgoing request workTraceConfig callbacks on ClientSession

These surfaces report different facts. An access entry has the final response and elapsed time. A trace callback has a request-stage event and its event data. Use the surface that matches the question being investigated rather than treating the two records as the same event.

References: aiohttp/log.py• L1-8 aiohttp/abc.py• L244-276 aiohttp/client.py• L317-318

Server logging

The server logging path reports protocol and application problems through named loggers. The access logger is separate so operators can route request records independently from server errors and other library messages.

The standard logger names identify the broad source of a message:

  • aiohttp.access for access records.
  • aiohttp.server for server errors and debug messages.
  • aiohttp.web for web-layer messages.
  • aiohttp.client for client messages.
  • aiohttp.internal and aiohttp.websocket for internal and WebSocket messages.

References: aiohttp/log.py• L1-8 aiohttp/web_protocol.py• L33-34 aiohttp/web_protocol.py• L593-598

Access-log integration

The access-log path emits one record after the response is prepared and written. It passes the request, response, and elapsed request time to a configurable access logger. A client disconnect still reaches this path when the server has enough response state to report the request.

The default AccessLogger formats common access data such as the remote address, request line, status, response size, elapsed time, request headers, response headers, and selected environment values. A custom logger can replace this formatter through the access-logger interfaces. Synchronous custom loggers run through an async wrapper so both synchronous and asynchronous logger contracts fit the request lifecycle.

The server avoids preparing an access entry when the selected logger is disabled. Set access_log=None to disable the access-log path, or provide access_log_class and access_log_format when the application needs a different record shape. The default formatter reports its own formatting errors through logging, while custom loggers define their own error behavior.

References: aiohttp/web_protocol.py• L98-118 aiohttp/web_protocol.py• L282-298 aiohttp/web_protocol.py• L582-591 aiohttp/web_protocol.py• L813-897 aiohttp/web_log.py• L20-64 aiohttp/web_log.py• L199-224 aiohttp/web_runner.py• L426-476

Client tracing

Client tracing provides extension points for code that needs timing, metrics, audit data, or correlation around ClientSession requests. A TraceConfig owns async signals. A callback receives the session, a per-request trace context, and typed event data.

The trace context is created for each configured trace setup at request start. Its factory can create a custom context and can receive the request-specific context supplied by the caller. This gives instrumentation one place to keep state across callbacks without changing the request API.

This diagram shows how a client request moves through trace callbacks and ends in either a response event or an exception event.

sequenceDiagram
    participant App as Application
    participant Session as ClientSession
    participant Trace as TraceConfig
    participant Net as Connector and request I/O

    App->>Session: Send request with trace context
    Session->>Trace: request start
    Trace-->>App: Run registered callbacks
    Session->>Net: Resolve, queue, connect, send
    Net->>Trace: Emit DNS, connection, header, and chunk events
    alt response succeeds
        Net-->>Session: Response
        Session->>Trace: redirect events as needed
        Session->>Trace: request end
    else request fails
        Net-->>Session: Exception
        Session->>Trace: request exception
    end

References: aiohttp/tracing.py• L44-123 aiohttp/tracing.py• L214-331 aiohttp/tracing.py• L333-468 aiohttp/client.py• L591-601 aiohttp/client.py• L761-766 aiohttp/client.py• L882-902 aiohttp/connector.py• L688-781 aiohttp/client_reqrep.py• L1546-1552

Trace event groups

The trace signals cover the request lifecycle and the work performed by the connector. Their typed parameters let instrumentation collect only the detail it needs.

Event groupWhat it describes
RequestStart, headers sent, body chunks sent, response chunks received, end, or exception
RedirectA response that causes the client to follow another URL
ConnectionQueue wait, connection creation, or connection reuse
DNSHost resolution start and end, plus cache hit or miss

TraceConfig freezes its signals when a session is created. Register callbacks before passing the configuration to ClientSession. Multiple trace configurations can observe the same request, which allows separate instrumentation concerns to keep separate contexts.

References: aiohttp/tracing.py• L54-123 aiohttp/tracing.py• L125-211 aiohttp/client.py• L414-416 aiohttp/client.py• L1442-1445 tests/test_tracing.py• L35-94

Test support

The test support layer lets tests choose the smallest useful level of realism. TestServer runs a complete web.Application, RawTestServer runs a request handler without an application, and TestClient sends real client requests to either server. make_mocked_request creates a request object for unit tests where socket setup is unnecessary or a rare state is hard to produce over the network.

The shared pytest setup adds fixtures for common network, TLS, event-loop, compression, and client-request conditions. These fixtures keep resource setup and cleanup in one place so feature tests can focus on the behavior under test.

References: aiohttp/test_utils.py• L1-45 aiohttp/test_utils.py• L63-223 aiohttp/test_utils.py• L225-299 aiohttp/test_utils.py• L497-535 aiohttp/test_utils.py• L566-682 tests/conftest.py• L24-71

Application fixtures

TestServer starts an application on a local socket and builds URLs rooted at the bound address. TestClient owns the matching client session and tracks responses and WebSocket connections so its close operation can release them before it stops the server. Both objects support async context managers, which makes setup and teardown follow the test scope.

The test-server boundary also carries runner settings to the correct server layer. Application-backed servers pass runner options to the application runner. Raw servers keep request-handler options separate from runner controls such as shutdown_timeout. This keeps raw-server shutdown behavior independent from handler construction.

Use AioHTTPTestCase when a test class needs the same application, server, and client lifecycle through unittest hooks. The test class supplies get_application; setup then creates the server and client, and teardown closes the client and its server.

References: aiohttp/test_utils.py• L63-223 aiohttp/test_utils.py• L225-299 aiohttp/test_utils.py• L463-535 tests/test_test_utils.py• L69-123 tests/test_test_utils.py• L271-279

Client fixtures

The TestClient request methods mirror the ClientSession request interface while accepting a relative path rooted at the test server. It also supports WebSocket requests and exposes the underlying session when a test needs client-specific controls. The default test cookie jar permits cookies for the local IP address, and retries are disabled so a test sees the first server interaction directly.

The client tracks open response and WebSocket objects. Closing the client closes those objects, then the session, and finally the test server. This order prevents a test from leaving network resources behind and makes repeated close calls safe.

Tests can inject a custom cookie jar to exercise client behavior when response-cookie processing fails. The client must release the connector slot before it reports that error, so a later request can still use the same client. Cookie-jar tests also protect the client cookie contract across domain and path scope, persistence, caller-owned cookie objects, and extreme expiry values.

The options accepted by TestClient follow the typed ClientSession option contract. Type checkers can therefore report unknown or wrongly typed client settings before a test runs.

References: aiohttp/test_utils.py• L225-265 aiohttp/test_utils.py• L291-309 aiohttp/test_utils.py• L308-461 aiohttp/test_utils.py• L463-495 tests/test_test_utils.py• L135-168 tests/test_test_utils.py• L237-268 tests/test_client_functional.py• L3022-3063 tests/test_cookiejar.py• L820-866 tests/test_cookiejar.py• L1473-1504 tests/test_cookiejar.py• L1963-1982

Unit request fixtures

make_mocked_request creates a web.Request with controlled headers, URL, payload, transport, protocol, writer, application, route match data, and request parsing limits. It is intended for focused unit tests, especially when a full server would add noise or when the test must model a transport or request state that is difficult to trigger in a live exchange.

The fixture supplies safe defaults for the request environment, including the default limit for form fields. It preserves header bytes that use the parser's surrogate-escape convention, so tests can model header values that are not plain UTF-8 without changing their raw form. Pass only the parts that matter to the test, and set request limits explicitly when the test must match an application with custom limits. Use a live TestServer plus TestClient when the behavior depends on real parsing, connection handling, or response I/O.

References: aiohttp/test_utils.py• L537-682 tests/test_test_utils.py• L176-235

  • Instrumentation covers client trace callbacks and other instrumentation choices.
  • Test harness usage covers patterns for selecting and using the test fixtures.
  • Client state and interception covers client sessions, middleware, and request interception around outgoing calls.
  • Server request processing covers the incoming request path that produces responses and access-log records.

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the access-log interfaces, runner options, and request-handler invocation aligned. A mismatch can reject a custom logger or stop records from receiving the final response state.
  • Keep every new client lifecycle stage connected across the trace signal, typed parameter, event sender, and the client or connector call site.
  • Keep trace context creation and signal freezing aligned with session construction. Callers must attach instrumentation before the session freezes its configurations.
  • Keep TestClient resource tracking aligned with its close order when adding a response or socket-like client resource.
  • Keep test-server URL creation aligned with socket binding when changing host, port, scheme, or socket-factory behavior.
  • Keep runner keyword contracts aligned with the layer that consumes them. In particular, raw-server shutdown settings must not enter request-handler options.
  • Keep make_mocked_request limits aligned with Request construction when request-size or form-field limits change. A unit fixture that uses different limits can hide an application boundary.
  • Keep mocked request header encoding aligned with the parser's surrogate-escape behavior. A mismatch can change raw header bytes in unit tests.
  • Keep custom cookie-jar error paths aligned with connector release and cookie scope rules. A failure in response-cookie processing must not hold a client connection or widen a host-only cookie.

Important failure modes

TriggerConsequenceGuard
Access logging is disabled or its logger level is below INFONo access entry is formatted or emittedEnable the access logger and use an appropriate log level
A custom access logger does not implement the required sync or async contractServer setup rejects it or request logging cannot runDerive from the matching access-logger abstract class
A trace callback is added after ClientSession constructionThe frozen signal rejects the late registrationRegister callbacks before passing TraceConfig to the session
Response-cookie processing raises inside a client requestA connector slot can remain busy and block later requestsRelease the connection before propagating the cookie-processing error
A raw-server runner option is passed as a request-handler optionHandler creation can drop custom settings or apply shutdown behavior at the wrong layerKeep shutdown_timeout with the runner and handler options with Server
A mocked request uses default field limits while the application uses custom limitsA unit test can miss a form-field limit errorPass the application limit to make_mocked_request
A mocked request does not preserve parser-escaped header bytesA unit test can change or reject a header value that a live parser would preserveUse the fixture's parser-compatible header handling
A test uses TestClient.session with a relative URLThe underlying session cannot add the test-server rootUse a TestClient method for relative paths or make_url for an absolute URL
A test skips client or server closeResponses, WebSockets, sessions, or sockets can remain openUse async context managers or await close() in teardown

Key files

FileWhy to read it
aiohttp/web_log.pyDefines the default access record and its format extension points.
aiohttp/abc.pyDefines the synchronous and asynchronous access-log contracts.
aiohttp/web_protocol.pyShows when access records are enabled and emitted in the server request lifecycle.
aiohttp/web_runner.pyShows how application-level access-log settings reach the server.
aiohttp/tracing.pyDefines trace configurations, contexts, signals, and event data.
aiohttp/client.pyShows how tracing attaches to a session and follows request success, redirects, and failure.
aiohttp/connector.pyShows connection and DNS trace extension points.
aiohttp/test_utils.pyDefines application servers, raw servers, clients, mocked requests, typed option boundaries, and test-case lifecycle support.
tests/conftest.pyDefines shared pytest fixtures for controlled network and runtime conditions.
tests/test_client_functional.pyShows application-backed client fixtures checking connection release after cookie-processing errors.
tests/test_cookiejar.pyShows the cookie scope, persistence, ownership, and expiry contracts used by client tests.