You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为FastAPI路由的OpenTelemetry Span添加用户ID属性?

Adding Custom User ID Attribute to OpenTelemetry Spans in FastAPI

No problem at all! Since you've already instrumented your FastAPI app with OpenTelemetry, adding the user ID as a custom attribute (tag) to your request spans is straightforward. Here's how to modify your code:

Updated main.py Code

from typing import Dict
import fastapi
from opentelemetry import trace
from opentelemetry.sdk.trace.export import (
    ConsoleSpanExporter,
    SimpleExportSpanProcessor,
)
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.sdk.trace import TracerProvider

trace.set_tracer_provider(TracerProvider())
trace.get_tracer_provider().add_span_processor(
    SimpleExportSpanProcessor(ConsoleSpanExporter())
)

app = fastapi.FastAPI()

@app.get("/user/{id}")
async def get_user(id: int) -> Dict[str, str]:
    """Test endpoint."""
    # Get the currently active span for this request
    current_span = trace.get_current_span()
    # Add the user ID as a custom attribute (tag)
    current_span.set_attribute("user.id", id)
    return {"message": "hello user!"}

FastAPIInstrumentor.instrument_app(app)

How This Works

  • trace.get_current_span() fetches the active span that's automatically created by the FastAPI OpenTelemetry instrumentation for each incoming request.
  • set_attribute(key, value) adds your custom tag to the span. You can use any meaningful key name (following OpenTelemetry naming conventions, using dots for hierarchy is a good practice like user.id).

Verify the Result

Run your app with uvicorn main:app --reload, then send a request to http://localhost:8000/user/123. Check your console output—you'll see the attributes section of the span now includes "user.id": 123.

If you need to add attributes to spans in multiple endpoints, you could even wrap this logic into a dependency to keep your code DRY!

内容的提问来源于stack exchange,提问作者louis_guitton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:52:58