如何解决如何为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!"}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。