向跟踪的范围添加标记对于以后分析跟踪数据并根据需要的标记对其进行切片和分割非常有用。
在阅读了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添加到span?
发布于 2020-09-19 23:04:45
在阅读了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!"}https://stackoverflow.com/questions/63970177
复制相似问题