Skip to content

Trace And LoggedΒΆ

A decorator that wraps a function in an OpenTelemetry span and logs its inputs, outputs, and exceptions.

ClassesΒΆ

TraceFilterConfig ΒΆ

TraceFilterConfig()

Configuration for filtering which operations get traced.

Source code in src/flock/logging/trace_and_logged.py
def __init__(self):
    self.services: set[str] | None = None  # Whitelist: only trace these services
    self.ignore_operations: set[str] = (
        set()
    )  # Blacklist: never trace these operations
    # FLOCK_TRACE_LEVEL: `agents` traces agent work, `all` also Flock's internals
    self.level: str = "agents"
    # FLOCK_TRACE_MAX_ATTRIBUTE_BYTES: longer inputs and outputs are cut (0: no cap)
    self.max_attribute_bytes: int = 4096

Methods:ΒΆ

hides ΒΆ
hides(owner: object) -> bool

Whether a call on owner is one of Flock's internals left out at this level.

Classes marked __trace_level__ = "all" (and their subclasses) are checked at call time too, since the hooks they inherit were wrapped in their base class.

Source code in src/flock/logging/trace_and_logged.py
def hides(self, owner: object) -> bool:
    """Whether a call on ``owner`` is one of Flock's internals left out at this level.

    Classes marked ``__trace_level__ = "all"`` (and their subclasses) are
    checked at call time too, since the hooks they inherit were wrapped in
    their base class.
    """
    return (
        self.level != "all"
        and getattr(type(owner), "__trace_level__", "agents") == "all"
    )
should_trace ΒΆ
should_trace(service: str, operation: str) -> bool

Check if an operation should be traced based on filters.

Parameters:

Name Type Description Default
service str

Service name (e.g., "Flock", "Agent")

required
operation str

Full operation name (e.g., "Flock.publish")

required

Returns:

Type Description
bool

True if should trace, False otherwise

Source code in src/flock/logging/trace_and_logged.py
def should_trace(self, service: str, operation: str) -> bool:
    """Check if an operation should be traced based on filters.

    Args:
        service: Service name (e.g., "Flock", "Agent")
        operation: Full operation name (e.g., "Flock.publish")

    Returns:
        True if should trace, False otherwise
    """
    # Check blacklist first (highest priority)
    if operation in self.ignore_operations:
        return False

    # Check whitelist if configured
    if self.services is not None:
        service_lower = service.lower()
        if service_lower not in self.services:
            return False

    return True

Functions:ΒΆ

capped ΒΆ

capped(value: str) -> str

An input or output attribute within FLOCK_TRACE_MAX_ATTRIBUTE_BYTES.

A longer value becomes JSON that says it was cut and how large it was, with as much of its start as preview as fits in the cap, escaping and marker included; the cut never splits a character.

Source code in src/flock/logging/trace_and_logged.py
def capped(value: str) -> str:
    """An input or output attribute within FLOCK_TRACE_MAX_ATTRIBUTE_BYTES.

    A longer value becomes JSON that says it was cut and how large it was,
    with as much of its start as ``preview`` as fits in the cap, escaping and
    marker included; the cut never splits a character.
    """
    limit = _trace_filter_config.max_attribute_bytes
    encoded = value.encode()
    if limit <= 0 or len(encoded) <= limit:
        return value

    def marker(preview: str) -> str:
        return json.dumps(
            {"truncated": True, "bytes": len(encoded), "preview": preview},
            ensure_ascii=False,
        )

    # The value's start that fits next to the marker; escaping can make the
    # preview longer than its bytes, so it shrinks until the whole fits
    room = max(0, limit - len(marker("").encode()))
    preview = encoded[:room].decode(errors="ignore")
    while preview:
        excess = len(marker(preview).encode()) - limit
        if excess <= 0:
            break
        preview = preview[: len(preview) - max(1, excess // 6)]
    return marker(preview)

run_attributes ΒΆ

run_attributes(correlation_id: object) -> dict[str, str]

A run's correlation as the attributes observability tools group traces by (#681): Langfuse sessions read session.id, Opik threads gen_ai.conversation.id.

Source code in src/flock/logging/trace_and_logged.py
def run_attributes(correlation_id: object) -> dict[str, str]:
    """A run's correlation as the attributes observability tools group traces by
    (#681): Langfuse sessions read ``session.id``, Opik threads
    ``gen_ai.conversation.id``."""
    value = str(correlation_id)
    return {"session.id": value, "gen_ai.conversation.id": value}

traced_and_logged ΒΆ

traced_and_logged(func)

A decorator that wraps a function in an OpenTelemetry span.

Creates proper parent-child span relationships and extracts relevant attributes for observability in Grafana/Jaeger.

Automatically extracts: - Agent name and description - Correlation ID and task ID from Context - Class and method names - Exception information

Supports both synchronous and asynchronous functions.

Source code in src/flock/logging/trace_and_logged.py
def traced_and_logged(func):
    """A decorator that wraps a function in an OpenTelemetry span.

    Creates proper parent-child span relationships and extracts relevant
    attributes for observability in Grafana/Jaeger.

    Automatically extracts:
    - Agent name and description
    - Correlation ID and task ID from Context
    - Class and method names
    - Exception information

    Supports both synchronous and asynchronous functions.
    """
    if inspect.iscoroutinefunction(func):

        @functools.wraps(func)
        async def async_wrapper(*args, **kwargs):
            attributes, span_name = _extract_span_attributes(func, args, kwargs)

            # Check if we should trace this operation
            service_name = span_name.split(".")[0] if "." in span_name else span_name
            if not _trace_filter_config.should_trace(service_name, span_name) or (
                args and _trace_filter_config.hides(args[0])
            ):
                # Skip tracing, just call the function
                return await func(*args, **kwargs)

            with tracer.start_as_current_span(span_name) as span:
                # Set all extracted attributes
                for key, value in attributes.items():
                    span.set_attribute(key, value)

                try:
                    result = await func(*args, **kwargs)

                    # Capture output value as JSON
                    try:
                        serialized_result = _serialize_value(result)
                        span.set_attribute(
                            "output.value",
                            capped(json.dumps(serialized_result, default=str)),
                        )
                    except Exception as e:
                        span.set_attribute("output.value", capped(str(result)))
                        span.set_attribute("output.serialization_error", str(e))

                    # Set result type and metadata
                    if result is not None:
                        span.set_attribute("output.type", type(result).__name__)
                        if hasattr(result, "__len__"):
                            try:
                                span.set_attribute("output.length", len(result))
                            except TypeError:
                                pass

                    _record_run(span, attributes, result)
                    span.set_status(Status(StatusCode.OK))
                    logger.debug(f"{span_name} executed successfully")
                    return result

                except Exception as e:
                    span.set_status(Status(StatusCode.ERROR, str(e)))
                    span.record_exception(e)
                    logger.exception(f"Error in {span_name}", error=str(e))
                    raise

        return async_wrapper

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        attributes, span_name = _extract_span_attributes(func, args, kwargs)

        # Check if we should trace this operation
        service_name = span_name.split(".")[0] if "." in span_name else span_name
        if not _trace_filter_config.should_trace(service_name, span_name) or (
            args and _trace_filter_config.hides(args[0])
        ):
            # Skip tracing, just call the function
            return func(*args, **kwargs)

        with tracer.start_as_current_span(span_name) as span:
            # Set all extracted attributes
            for key, value in attributes.items():
                span.set_attribute(key, value)

            try:
                result = func(*args, **kwargs)

                # Capture output value as JSON
                try:
                    serialized_result = _serialize_value(result)
                    span.set_attribute(
                        "output.value",
                        capped(json.dumps(serialized_result, default=str)),
                    )
                except Exception as e:
                    span.set_attribute("output.value", capped(str(result)))
                    span.set_attribute("output.serialization_error", str(e))

                # Set result type and metadata
                if result is not None:
                    span.set_attribute("output.type", type(result).__name__)
                    if hasattr(result, "__len__"):
                        try:
                            span.set_attribute("output.length", len(result))
                        except TypeError:
                            pass

                _record_run(span, attributes, result)
                span.set_status(Status(StatusCode.OK))
                logger.debug(f"{span_name} executed successfully")
                return result

            except Exception as e:
                span.set_status(Status(StatusCode.ERROR, str(e)))
                span.record_exception(e)
                logger.exception(f"Error in {span_name}", error=str(e))
                raise

    return wrapper