Skip to content

Auto TraceΒΆ

Metaclass for automatic method tracing via OpenTelemetry.

ClassesΒΆ

CallerTraceMiddleware ΒΆ

CallerTraceMiddleware(app)

Continues the caller's trace (traceparent, baggage) when FastAPI's request spans are off, which also turns off FastAPI reading those headers. A request span a host's own instrumentation started stays the parent.

Source code in src/flock/logging/auto_trace.py
def __init__(self, app) -> None:
    self.app = app

AutoTracedMeta ΒΆ

Bases: type

Metaclass that automatically applies @traced_and_logged to all public methods.

This enables automatic OpenTelemetry span creation and debug logging for all method calls on classes using this metaclass.

Control via environment variable

FLOCK_AUTO_TRACE=true - Enable auto-tracing (default) FLOCK_AUTO_TRACE=false - Disable auto-tracing

Example

class Agent(metaclass=AutoTracedMeta): def execute(self, ctx, artifacts): # Automatically traced and logged ...

Methods:ΒΆ

__new__ ΒΆ
__new__(mcs, name, bases, namespace, **kwargs)

Create a new class with auto-traced methods.

Source code in src/flock/logging/auto_trace.py
def __new__(mcs, name, bases, namespace, **kwargs):
    """Create a new class with auto-traced methods."""
    if not ENABLE_AUTO_TRACE:
        # If auto-tracing is disabled, return the class unchanged
        return super().__new__(mcs, name, bases, namespace, **kwargs)

    # Methods of a class (or a single method) marked `all` are Flock's internals:
    # traced only at FLOCK_TRACE_LEVEL=all (#601)
    class_level = namespace.get("__trace_level__", "agents")

    # Apply @traced_and_logged to all public methods
    for attr_name, attr_value in list(namespace.items()):
        # Skip private methods (starting with _)
        if attr_name.startswith("_"):
            continue

        # Skip non-callables
        if not callable(attr_value):
            continue

        # Skip if already traced
        if getattr(attr_value, "_traced", False):
            continue

        # Skip if explicitly marked to skip tracing
        if getattr(attr_value, "_skip_trace", False):
            continue

        function = getattr(
            attr_value, "__func__", attr_value
        )  # a staticmethod's function
        if (
            getattr(function, "_trace_level", class_level) == "all"
            and _trace_filter_config.level != "all"
        ):
            continue

        # Apply the decorator
        traced_func = traced_and_logged(attr_value)
        traced_func._traced = True  # Mark as traced to avoid double-wrapping
        namespace[attr_name] = traced_func

    return super().__new__(mcs, name, bases, namespace, **kwargs)

Functions:ΒΆ

http_telemetry ΒΆ

http_telemetry() -> dict

FastAPI's own spans of the server's requests: at FLOCK_TRACE_LEVEL=all only.

Source code in src/flock/logging/auto_trace.py
def http_telemetry() -> dict:
    """FastAPI's own spans of the server's requests: at FLOCK_TRACE_LEVEL=all only."""
    return {"tracing": _trace_filter_config.level == "all"}

continue_caller_traces ΒΆ

continue_caller_traces(app) -> None

Below FLOCK_TRACE_LEVEL=all, agent work an HTTP request starts still joins the caller's trace.

Source code in src/flock/logging/auto_trace.py
def continue_caller_traces(app) -> None:
    """Below FLOCK_TRACE_LEVEL=all, agent work an HTTP request starts still
    joins the caller's trace."""
    if _trace_filter_config.level != "all":
        app.add_middleware(CallerTraceMiddleware)

skip_trace ΒΆ

skip_trace(func)

Decorator to mark a method to skip auto-tracing.

Use this for methods that are called very frequently or are not interesting for debugging purposes.

Example

class Agent(metaclass=AutoTracedMeta): @skip_trace def _internal_helper(self): # Not traced ...

Source code in src/flock/logging/auto_trace.py
def skip_trace(func):
    """Decorator to mark a method to skip auto-tracing.

    Use this for methods that are called very frequently or are not
    interesting for debugging purposes.

    Example:
        class Agent(metaclass=AutoTracedMeta):
            @skip_trace
            def _internal_helper(self):
                # Not traced
                ...
    """
    func._skip_trace = True
    return func

trace_level ΒΆ

trace_level(level: str)

Decorator: trace this method only at FLOCK_TRACE_LEVEL=level.

all marks Flock's internals, such as building and registering agents; a whole class sets __trace_level__ = "all" instead.

Source code in src/flock/logging/auto_trace.py
def trace_level(level: str):
    """Decorator: trace this method only at ``FLOCK_TRACE_LEVEL=level``.

    ``all`` marks Flock's internals, such as building and registering agents;
    a whole class sets ``__trace_level__ = "all"`` instead.
    """
    if level not in TRACE_LEVELS:
        raise ValueError(f"trace level must be one of {TRACE_LEVELS}, not {level!r}")

    def mark(func):
        func._trace_level = level
        return func

    return mark