AIOHTTP Middleware Request Logging

Instrument aiohttp with middleware that logs every request with duration, status, and client identity, sampling noisy health probes.

PythonResilience

Code

snippet
import logging
import time
import uuid

from aiohttp import web

logger = logging.getLogger('request')
logging.basicConfig(
    level=logging.INFO,
    format='%(levelname)s %(name)s %(message)s',
)

routes = web.RouteTableDef()


@web.middleware
async def request_logging(request: web.Request, handler):
    if request.path == '/healthz':  # 探针流量不进日志
        return await handler(request)

    request_id = request.headers.get('X-Request-Id', str(uuid.uuid4())[:8])
    started = time.perf_counter()

    try:
        response = await handler(request)
    except web.HTTPException:
        raise
    except Exception:
        logger.exception(
            'request failed rid=%s path=%s', request_id, request.path
        )
        return web.json_response({'error': 'internal error'}, status=500)

    elapsed_ms = (time.perf_counter() - started) * 1000
    logger.info(
        'rid=%s %s %s -> %d %.1fms client=%s',
        request_id, request.method, request.path,
        response.status, elapsed_ms,
        request.remote or '-',
    )
    response.headers['X-Request-Id'] = request_id
    return response


@routes.get('/orders/{id}')
async def get_order(request: web.Request) -> web.Response:
    if request.match_info['id'] == '404':
        raise web.HTTPNotFound(text='no such order')
    return web.json_response({'id': request.match_info['id']})


app = web.Application(middlewares=[request_logging])
app.add_routes(routes)
web.run_app(app, port=8080)