Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ttti07 opened this issue Oct 21, 2023 · 0 comments
Open

Comments

@ttti07
Copy link

ttti07 commented Oct 21, 2023

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant