【问题标题】:How to set an OpenTelemetry span attribute for a FastAPI route?如何为 FastAPI 路由设置 OpenTelemetry 跨度属性?
【发布时间】:2020-09-19 15:04:45
【问题描述】:

将标签添加到跟踪的跨度对于以后分析跟踪数据并按所需标签切片和切块非常有用。

在阅读了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 添加到跨度?

【问题讨论】:

    标签: fastapi telemetry open-telemetry


    【解决方案1】:

    在阅读了 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!"}
    

    【讨论】:

      猜你喜欢
      • 2015-02-16
      • 1970-01-01
      • 2018-01-14
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 2011-08-13
      相关资源
      最近更新 更多