在Python OpenTelemetry中创建一个顶级Span。

huangapple go评论75阅读模式
英文:

creating a top level span in python opentelemetry

问题

我有一个Python服务,我正在尝试添加opentelemetry。我正在手动跟踪用户请求和子任务,似乎工作正常:我能够查看Jaeger中的跨度。

然而,我的系统可能会决定在请求中间启动一个后台的asyncio任务。请求会立即结束,但后台任务将永远继续下去。如果我将这个任务调用的代码跟踪为跨度,它们最终会成为请求跨度的子跨度,尽管请求已经结束。我更希望将这些跨度显示为顶级跨度,而不是任何父跨度的子跨度。

文档似乎没有解决这种特殊情况,所以我正在尝试找到方法。

这是我正在尝试的简化版本:

from opentelemetry import trace
from opentelemetry import context

tracer = trace.get_tracer(__name__)
ROOT_CONTEXT = context.get_current()
tasks = set()

async def background_task(some_req_info):
    with tracer.start_as_current_span("background task", context=ROOT_CONTEXT):
        # 做一些事情
        ...

async def request(some_req_info):
    with tracer.start_as_current_span("request"):
        # 更多逻辑
        task = asyncio.create_task(background_task(some_req_info))
        tasks.add(task)
        task.add_done_callback(tasks.discard)

如何在后台任务中实现没有父跨度的跨度?

英文:

I have a python service that I am trying to add opentelemetry to. I am manually tracking user requests and subtasks and this seems to work ok: I am able to look at the spans in jaeger.

However, my system may decide to start a background asyncio task in the middle of a request. The request will end immediately, but the background task will go on forever. If I track code called by this task as spans, they end up being children of the request's span, although the request already ended. I'd rather prefer to show these spans as top level, like not children of any parent.

The documentation seems not to address this specific case, so I am trying to find the way

This is a simplified version of what I am attempting:

from opentelemetry import trace
from opentelemetry import context

tracer = trace.get_tracer(__name__)
ROOT_CONTEXT = context.get_current()
tasks = set()

async def background_task(some_req_info):
    with tracer.start_as_current_span("background task", context=ROOT_CONTEXT):
        # do stuff
        ...

async def request(some_req_info):
    with tracer.start_as_current_span("request"):
        # more logic
        task = asyncio.create_task(background_task(some_req_info))
        tasks.add(task)
        task.add_done_callback(tasks.discard)

How can I achieve parent-less spans in background tasks?

答案1

得分: 0

OK,所以我实际上在Jaeger中测量了错误的东西。我发布的代码按预期工作。我将保留这个问题,以节省下一个想要解决这个特定问题的开发人员的时间。

英文:

OK, so I was actually measuring the wrong thing in jaeger. The code I posted works as expected. I am leaving this question here to save hours to the next developer wanting to solve this particular problem.

huangapple
  • 本文由 发表于 2023年6月8日 17:46:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定