Uvicorn本身不支持OpenTelemetry自动埋点,必须在uvicorn.run()前完成FastAPIInstrumentor.instrument_app(app)和TracerProvider初始化,否则Span静默丢弃;跨服务调用须用instrumented异步客户端(如httpx.AsyncClient+HTTPXClientInstrumentor),且Nginx等网关需透传traceparent头。

Uvicorn 本身不直接支持 OpenTelemetry 自动埋点,必须通过 FastAPI(或其他 ASGI 框架)层接入,且关键动作必须在 uvicorn.run() 之前完成——否则所有 Span 静默丢弃。
FastAPIInstrumentor.instrument_app() 必须在 uvicorn.run() 前调用
Uvicorn 只是 ASGI 服务器,它不参与 Span 创建;真正生成入口 Span 的是 FastAPIInstrumentor 对路由中间件的注入。如果把 instrument_app() 放在 uvicorn.run() 后面,或者放在异步启动逻辑里(比如 asyncio.run() 内部),instrumentation 就不会生效。
- ✅ 正确顺序:
app = FastAPI()→FastAPIInstrumentor.instrument_app(app)→uvicorn.run(app, ...) - ❌ 错误写法:在
if __name__ == "__main__":块里先uvicorn.run(),再调 instrument —— 此时 app 已被封装,instrument 失效 - ⚠️ 注意:
instrument_app()不抛异常,失败时仅静默跳过,需靠日志或手动检查request.headers.get("traceparent")是否存在来验证
TracerProvider 必须提前初始化并绑定 Resource
OpenTelemetry SDK 要求全局 TracerProvider 在任何 get_tracer() 调用前就位,否则返回空 tracer,Span 全部丢失。只装包、不设 provider 是最常见断链原因。
- 必须显式创建:
TracerProvider(resource=Resource.create({SERVICE_NAME: "my-service"})) - 必须绑定导出器:用
BatchSpanProcessor(非SimpleSpanProcessor),否则压测时主线程阻塞、超时频发 - 示例片段:
from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.resources import Resource from opentelemetry.exporter.jaeger.thrift import JaegerExporter from opentelemetry.sdk.trace.export import BatchSpanProcessor resource = Resource.create({SERVICE_NAME: "user-api"}) provider = TracerProvider(resource=resource) processor = BatchSpanProcessor(JaegerExporter()) provider.add_span_processor(processor) trace.set_tracer_provider(provider)
跨服务 HTTP 调用必须用 instrumented 异步客户端
FastAPI 路由内若用 httpx.get() 或 requests.get() 发起下游请求,traceparent 头不会自动注入,链路在第一跳就断裂。Uvicorn 的异步特性决定了必须用 httpx.AsyncClient + 对应插桩器。
Uvicorn 0.52.1 是 Python ASGI Web 服务器,提供异步应用服务及 WebSocket 支持,常用于 FastAPI、Starlette 等应用的开发和部署。本下载为官方 PyPI 通用 wheel 包,可使用 pip 安装,并由包管理器处理所需依赖。
- ✅ 必须安装:
opentelemetry-instrumentation-httpx - ✅ 必须调用:
HTTPXClientInstrumentor().instrument()(在uvicorn.run()前) - ❌ 禁用:
httpx.Client(同步)、aiohttp(除非额外调用AIOHttpClientInstrumentor().instrument()) - 验证方式:在路由中打印
request.headers.get("traceparent"),上游有值、下游服务入口也应能读到
别让 Nginx 或网关吃掉 traceparent 头
即使代码全配对,如果前端有 Nginx、Kong 或 API 网关,它们默认可能过滤或重写 traceparent 和 tracestate。这些头必须透传,且大小写敏感(W3C 规范要求小写)。
- Nginx 示例配置:
proxy_pass_request_headers on;+ 显式放行:proxy_set_header traceparent $http_traceparent; - Kubernetes Ingress:确认 annotation 中未设置
nginx.ingress.kubernetes.io/configuration-snippet删除了自定义 header - Jaeger UI 查不到 Span?优先查下游服务是否收到
traceparent,而不是怀疑 exporter 配置
最容易被忽略的是:Uvicorn 进程启动后,instrumentation 就已冻结;任何后续的 provider 设置、instrument 调用都无效。所有初始化必须在 uvicorn.run() 之前一次性完成,且顺序不可颠倒。










