如何为FastAPI路由设置OpenTelemetry跨度属性?

问题描述

在跟踪范围内添加标签对于以后分析跟踪数据并通过所需标签将其切片和切块非常有用。

在阅读OpenTelemetry docs之后,我想不出一种将自定义标签添加到跨度的方法

这是我的示例FastAPI应用程序,已经使用OpenTelemetry进行了检测:

"""main.py"""
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."""
    return {"message": "hello user!"}


FastAPIInstrumentor.instrument_app(app)

您可以使用uvicorn main:app --reload

运行它

如何将用户ID添加到跨度?

解决方法

阅读ASGI工具的OpenTelemetryMiddleware(here)的源代码后,我意识到您可以简单地获取当前范围,设置标签(或属性),并且将返回当前范围及其所有属性

@app.get("/user/{id}")
async def get_user(id: int) -> Dict[str,str]:
    """Test endpoint."""
    # Instrument the user id as a span tag
    current_span = trace.get_current_span()
    if current_span:
        current_span.set_attribute("user_id",id)

    return {"message": "hello user!"}