如何为 structlog 添加 request-id 并追踪全链路?

解读

国内生产级 FastAPI 项目普遍采用 structlog 做结构化日志,面试官问“request-id 全链路追踪”并不是让你背文档,而是考察三点:

  1. 能否在框架入口(ASGI 中间件)统一生成 request-id 并写进上下文;
  2. 能否把该 ID 透传给下游 HTTP/RPC/数据库,确保“一码到底”;
  3. 能否让日志在任何地方都能无参取出 request-id,且对业务代码零侵入。
    如果只说“用 middleware 加 header”只能得 60 分,必须给出可落地的 Python 代码、线程/协程安全方案以及灰度部署时的兼容性考虑。

知识点

  1. ASGI 中间件与 contextvars 的协程安全
  2. structlog 的 processors 链与 bind/context 机制
  3. starlette.middleware.base.BaseHTTPMiddleware 的“二次包裹”缺陷与纯 ASGI 中间件写法
  4. 下游透传:aiohttp/httpx 的 EventHook、grpc.interceptors、SQLAlchemy 的 connection_callable
  5. 可观测性三件套:Log(结构化日志)、Trace(OpenTelemetry)、Metric(Prometheus)如何共用同一个 trace-id
  6. 国内网关(阿里云 ALB、腾讯云 CLB、Nginx ingress)已有 x-request-id 时的覆盖策略与合规要求(等保 2.0 日志留痕)

答案

生产级落地代码(可直接写进简历项目):

# 1. 依赖
import uuid
import contextvars
from typing import Awaitable, Callable
from starlette.types import ASGIApp, Scope, Receive, Send
import structlog

# 2. 全局 contextvars,保证协程安全
_request_id_ctx: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="")

# 3. 纯 ASGI 中间件,避免 BaseHTTPMiddleware 的上下文泄漏
class RequestIdMiddleware:
    def __init__(self, app: ASGIApp) -> None:
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        # 优先取网关透传 ID,否则生成
        headers = dict(scope["headers"])
        request_id = (
            headers.get(b"x-request-id", b"").decode()
            or headers.get(b"x-trace-id", b"").decode()
            or uuid.uuid4().hex
        )

        # 写上下文
        token = _request_id_ctx.set(request_id)

        # 在 response header 中回传,方便前端排查
        async def send_wrapper(message):
            if message["type"] == "http.response.start":
                headers = message.setdefault("headers", [])
                headers.append((b"x-request-id", request_id.encode()))
            await send(message)

        try:
            await self.app(scope, receive, send_wrapper)
        finally:
            _request_id_ctx.reset(token)

# 4. structlog 处理器:把 contextvars 注入每条日志
def add_request_id(logger, method_name, event_dict):
    event_dict["request_id"] = _request_id_ctx.get()
    return event_dict

structlog.configure(
    processors=[
        add_request_id,
        structlog.stdlib.filter_by_level,
        structlog.stdlib.PositionalArgumentsFormatter(),
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.JSONRenderer(),
    ],
    context_class=dict,
    logger_factory=structlog.stdlib.LoggerFactory(),
    wrapper_class=structlog.stdlib.BoundLogger,
    cache_logger_on_first_use=True,
)

# 5. FastAPI 挂载
from fastapi import FastAPI
app = FastAPI()
app.add_middleware(RequestIdMiddleware)

# 6. 下游 HTTP 客户端自动透传
import httpx
async def inner_httpx():
    async with httpx.AsyncClient(
        event_hooks={"request": [lambda req: req.headers.update({"x-request-id": _request_id_ctx.get()})]}
    ) as client:
        ...

线程安全:contextvars 只在协程间传播,若代码里用到 ThreadPoolExecutor,需把 request_id 显式当参数传;
兼容灰度:新服务识别 x-request-id,老服务忽略,保证平滑上线;
等保合规:日志落盘时 request_id 与 user_id、IP、URL 一起写,保留 180 天。

拓展思考

  1. 如果公司全面接入 OpenTelemetry,可把 request-id 直接作为 trace-id 的子段,用 Baggage 把业务字段(tenant_id、user_id)带到下游,实现“三栈合一”(Log/Trace/Metric)。
  2. 对 WebSocket 长连接,request-id 只在握手阶段生成,后续消息帧可继续用同一条 ID,也可按消息再细分 message-id,面试时可讨论两种策略的优劣。
  3. 高并发场景下 uuid.uuid4().hex 的随机数性能可能成为瓶颈,可改用基于雪花算法的分布式 ID(如 leaf、uid-generator),并讲解如何保证时钟回拨安全。