Skip to content

Support @trace decorator using contextvars (similar to starlette-zipkin) #594

@ttti07

Description

@ttti07

I would like if aiozipkin support such a syntax below:

@trace(exclude_params=["auth"])
async def my_func(
    a: int,
    b: str,
    auth: str,
    c: dict[str, int],
):
    # ...


def other_func(a: int, b: list[str]):
    # ...
    x = get_my_array()
    y = get_my_str()

    with new_child_from_fls(name="calculate_then_do_something") as span:
        span.tag_input(x=x, y=y)
        r = calculate_result(x, y)
        r2 = do_something_more(r)
        span.tag_output(r2)

The main advantage of this design is,
it does not require tracer-context explicitly, by using contextvars (I'll call it as fiber-local storage, FLS),
so we don't have to modify existing functions.
In case of decorator, if span_name is not given, we can automatically get the function name.
We can also collect input args and return value of the function, and add tags (i.e. Span.tag(...)) for them automatically.
(That's what exclude_params exists for)

Actually I've already implemented it and tested it on python 3.10+, with fastapi.
After put @trace decorator to everywhere I want, two things were needed.

  • I created a tracer using az.create, and stored it in app context (e.g. fastapi.FastAPI.extra["tracer"] = tracer)
  • In a middleware function, for every request, get the tracer from the app context, then store the tracer and root span in FLS variables.
    • At the and of the middleware function, it's better to reset(=undo) FLS variables.

Firstly I saw decorator design from starlette-zipkin,
but I found out that starlette-zipkin's @trace decorator is not fiber-safe...

Anyway, is there any technical problem with this design?
Is it dangerous to use FLS variables?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions