AIOHTTP Middleware Request Logging
Instrument aiohttp with middleware that logs every request with duration, status, and client identity, sampling noisy health probes.
Code
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)How it works
AIOHTTP Middleware Request Logging keeps everything in the functions request_logging and get_order.
Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. The snippet’s external surface is web, all of it via aiohttp. except and web appears at a raise inside an except handler — it fires only while that failure type is already being handled.
Watch out for
aiohttpandloggingmust be installed first — the snippet imports them directly.- The guard
request.match_info['id'] == '404'short-circuits the flow with an earlyraisewhen its condition holds.
Using it
Entry signature: def request_logging(request: web.Request, handler)
The surface worth importing is request_logging; the helpers around it are private to the snippet.
Key statements
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']})
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)
Interactive Tools for This Topic
FAQ
- When is the exception raised?
- Inside an `except` handler — the `except` and `web` fires only while that failure type is already being handled, not on its own trigger.
- Are there third-party dependencies?
- `aiohttp` and `logging` — install them with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.