Skip to content

Tracing decorator for functions #2621

@hooverdc

Description

@hooverdc

Is your feature request related to a problem?
Tracing every use of a function is prone to error. It is very hard to do in some contexts, such as functions from a third party library that don't integrate with OTel, without lots of manual span management.

Describe the solution you'd like
I would like to have a first party tracing decorator.

Describe alternatives you've considered
I have rolled my own for now:

import functools
from contextlib import nullcontext
from typing import Callable

from opentelemetry import trace
from opentelemetry.trace import NonRecordingSpan


def traced(name: str) -> Callable:
    """Wrap a function in an OTel span."""

    def decorator(func: Callable):
        @functools.wraps(func)
        def wraps(*args, **kwargs):
            if isinstance(trace.get_current_span(), NonRecordingSpan):
                span = nullcontext()
            else:
                span = trace.get_tracer(func.__module__).start_as_current_span(name)
            
            with span:
                return func(*args, **kwargs)

        return wraps

    return decorator

Additional context
Honeycomb does something similar in their beeline module with the traced decorator.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions