Skip to content

clabe.logging.otel

AindOtelSettings

Bases: OtelSettings

AIND log-schema profile: tags runs with the fields from log-schema.

Every field is optional and settable in clabe.yml. Fields left unset are auto-populated at creation time where a default exists (hostname, rig_id, software_version); subject_id and user_id stay None until the session is registered. Any field can also be overridden at any time via clabe.logging.otel.enrich_attribute (this is also how one-off attributes such as instrument_id are set — they have no dedicated field).

See https://github.com/AllenNeuralDynamics/log-schema for the field definitions.

settings_customise_sources classmethod

settings_customise_sources(
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]

Customizes the settings sources to include the safe YAML settings source.

Parameters:

Name Type Description Default
settings_cls type[BaseSettings]

The settings class

required
init_settings PydanticBaseSettingsSource

The initial settings source

required
env_settings PydanticBaseSettingsSource

The environment settings source

required
dotenv_settings PydanticBaseSettingsSource

The dotenv settings source

required
file_secret_settings PydanticBaseSettingsSource

The file secret settings source

required

Returns:

Type Description
tuple[PydanticBaseSettingsSource, ...]

Tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources

Source code in src/clabe/settings.py
@classmethod
def settings_customise_sources(
    cls,
    settings_cls: type[ps.BaseSettings],
    init_settings: ps.PydanticBaseSettingsSource,
    env_settings: ps.PydanticBaseSettingsSource,
    dotenv_settings: ps.PydanticBaseSettingsSource,
    file_secret_settings: ps.PydanticBaseSettingsSource,
) -> tuple[ps.PydanticBaseSettingsSource, ...]:
    """
    Customizes the settings sources to include the safe YAML settings source.

    Args:
        settings_cls: The settings class
        init_settings: The initial settings source
        env_settings: The environment settings source
        dotenv_settings: The dotenv settings source
        file_secret_settings: The file secret settings source

    Returns:
        Tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources
    """
    yaml_sources = [
        _SafeYamlSettingsSource(settings_cls, yaml_file=p, yaml_config_section=cls.__yml_section__)
        for p in KNOWN_CONFIG_FILES
    ]
    # The in-memory document (--clabe-yml) ranks above every file
    return (
        init_settings,
        _InMemorySettingsSource(settings_cls, config_section=cls.__yml_section__),
        *yaml_sources,
        env_settings,
        dotenv_settings,
        file_secret_settings,
    )

resolved_service_name

resolved_service_name() -> str

Use the log-schema software_name as the "Service", falling back to service_name.

software_name is the producing application, which is exactly what service.name should identify. It is also emitted as the explicit software_name attribute (see initial_attributes) for log-schema consumers that key on that field by name.

Source code in src/clabe/logging/otel/_settings.py
def resolved_service_name(self) -> str:
    """Use the log-schema ``software_name`` as the "Service", falling back to ``service_name``.

    ``software_name`` is the producing application, which is exactly what ``service.name``
    should identify. It is also emitted as the explicit ``software_name`` attribute (see
    `initial_attributes`) for log-schema consumers that key on that field by name.
    """
    return self.software_name or self.service_name

initial_attributes

initial_attributes() -> dict[str, AttributeValue]

Resolve the log-schema fields, applying auto-defaults to any left unset in config.

Source code in src/clabe/logging/otel/_settings.py
def initial_attributes(self) -> dict[str, AttributeValue]:
    """Resolve the log-schema fields, applying auto-defaults to any left unset in config."""
    from ...aind.validators import get_aind_rig_name

    resolved: dict[str, str | None] = {
        "hostname": self.hostname or _default_hostname(),
        "software_name": self.software_name,
        "software_version": self.software_version
        or (_distribution_version(self.software_name) if self.software_name else None),
        "rig_id": self.rig_id or get_aind_rig_name(),
        "subject_id": self.subject_id,
        "user_id": self.user_id,
    }
    return {key: value for key, value in resolved.items() if value is not None}

session_attributes

session_attributes(
    session: Session,
) -> dict[str, AttributeValue]

Fill subject_id and user_id from the session (plus the base session name).

Source code in src/clabe/logging/otel/_settings.py
def session_attributes(self, session: "Session") -> dict[str, AttributeValue]:
    """Fill ``subject_id`` and ``user_id`` from the session (plus the base session name)."""
    attributes = super().session_attributes(session)
    if session.subject:
        attributes["subject_id"] = session.subject
    if session.experimenter:
        attributes["user_id"] = ", ".join(session.experimenter)
    return attributes

OtelSettings

Bases: ServiceSettings

OpenTelemetry transport settings read from the otel section of clabe.yml.

The base class is backend-agnostic: it configures how telemetry is shipped and tags a run with only its name. A profile enriches the run with domain identity by overriding the two population hooks:

  • initial_attributes — values known at process start (config + auto-defaults).
  • session_attributes — values derived from the session, once it is registered.

Both feed a single attribute bag that is stamped on every span and log. Attributes may also be set at any time during a run via clabe.logging.otel.enrich_attribute.

settings_customise_sources classmethod

settings_customise_sources(
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]

Customizes the settings sources to include the safe YAML settings source.

Parameters:

Name Type Description Default
settings_cls type[BaseSettings]

The settings class

required
init_settings PydanticBaseSettingsSource

The initial settings source

required
env_settings PydanticBaseSettingsSource

The environment settings source

required
dotenv_settings PydanticBaseSettingsSource

The dotenv settings source

required
file_secret_settings PydanticBaseSettingsSource

The file secret settings source

required

Returns:

Type Description
tuple[PydanticBaseSettingsSource, ...]

Tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources

Source code in src/clabe/settings.py
@classmethod
def settings_customise_sources(
    cls,
    settings_cls: type[ps.BaseSettings],
    init_settings: ps.PydanticBaseSettingsSource,
    env_settings: ps.PydanticBaseSettingsSource,
    dotenv_settings: ps.PydanticBaseSettingsSource,
    file_secret_settings: ps.PydanticBaseSettingsSource,
) -> tuple[ps.PydanticBaseSettingsSource, ...]:
    """
    Customizes the settings sources to include the safe YAML settings source.

    Args:
        settings_cls: The settings class
        init_settings: The initial settings source
        env_settings: The environment settings source
        dotenv_settings: The dotenv settings source
        file_secret_settings: The file secret settings source

    Returns:
        Tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources
    """
    yaml_sources = [
        _SafeYamlSettingsSource(settings_cls, yaml_file=p, yaml_config_section=cls.__yml_section__)
        for p in KNOWN_CONFIG_FILES
    ]
    # The in-memory document (--clabe-yml) ranks above every file
    return (
        init_settings,
        _InMemorySettingsSource(settings_cls, config_section=cls.__yml_section__),
        *yaml_sources,
        env_settings,
        dotenv_settings,
        file_secret_settings,
    )

resolved_service_name

resolved_service_name() -> str

The service.name resource attribute — the "Service" every span and log is tagged with.

Source code in src/clabe/logging/otel/_settings.py
def resolved_service_name(self) -> str:
    """The ``service.name`` resource attribute — the "Service" every span and log is tagged with."""
    return self.service_name

initial_attributes

initial_attributes() -> dict[str, AttributeValue]

Attributes known at process start: config values plus auto-resolved defaults.

This is stages 1 and 2 of population. Auto-defaults fill only fields left None in config, so an explicit clabe.yml value is never overwritten. The base profile adds nothing; keys whose resolved value is None are omitted.

Source code in src/clabe/logging/otel/_settings.py
def initial_attributes(self) -> dict[str, AttributeValue]:
    """Attributes known at process start: config values plus auto-resolved defaults.

    This is stages 1 and 2 of population. Auto-defaults fill only fields left ``None`` in
    config, so an explicit clabe.yml value is never overwritten. The base profile adds
    nothing; keys whose resolved value is ``None`` are omitted.
    """
    return {}

session_attributes

session_attributes(
    session: Session,
) -> dict[str, AttributeValue]

Attributes derived from the session, bound once the launcher registers it.

This is stage 3 of population and overrides any same-named value set earlier.

Source code in src/clabe/logging/otel/_settings.py
def session_attributes(self, session: "Session") -> dict[str, AttributeValue]:
    """Attributes derived from the session, bound once the launcher registers it.

    This is stage 3 of population and overrides any same-named value set earlier.
    """
    attributes: dict[str, AttributeValue] = {}
    if session.session_name:
        attributes["session_name"] = session.session_name
    return attributes

event

event(name: str, attributes: Attributes = None) -> None

Record a timestamped event on the current span.

Source code in src/clabe/logging/otel/_api.py
def event(name: str, attributes: Attributes = None) -> None:
    """Record a timestamped event on the current span."""
    trace.get_current_span().add_event(name, attributes=attributes)

record_exception

record_exception(exception: BaseException) -> None

Record an exception on the current span and mark it as failed.

Takes BaseException so interrupts (KeyboardInterrupt), which OTel's own span handling skips, can be recorded as failures too.

Source code in src/clabe/logging/otel/_api.py
def record_exception(exception: BaseException) -> None:
    """Record an exception on the current span and mark it as failed.

    Takes ``BaseException`` so interrupts (``KeyboardInterrupt``), which OTel's own span
    handling skips, can be recorded as failures too.
    """
    current = trace.get_current_span()
    current.record_exception(exception)
    current.set_status(Status(StatusCode.ERROR))

set_attribute

set_attribute(key: str, value: AttributeValue) -> None

Set a single attribute on the current span.

Source code in src/clabe/logging/otel/_api.py
def set_attribute(key: str, value: AttributeValue) -> None:
    """Set a single attribute on the current span."""
    trace.get_current_span().set_attribute(key, value)

span

span(
    name: str, attributes: Attributes = None
) -> Generator[Span, None, None]

Open a span nested under the current experiment trace.

Parameters:

Name Type Description Default
name str

Name of the span.

required
attributes Attributes

Optional attributes set when the span starts.

None

Yields:

Type Description
Span

The started span, so callers can enrich it further.

Source code in src/clabe/logging/otel/_api.py
@contextmanager
def span(name: str, attributes: Attributes = None) -> Generator[Span, None, None]:
    """Open a span nested under the current experiment trace.

    Args:
        name: Name of the span.
        attributes: Optional attributes set when the span starts.

    Yields:
        The started span, so callers can enrich it further.
    """
    with trace.get_tracer(_TRACER_NAME).start_as_current_span(name, attributes=attributes) as current:
        yield current

run_span

run_span(
    launcher: Launcher, experiment_name: str | None = None
) -> Generator[Span, None, None]

Instrument a launcher run: install telemetry if enabled, then open the root span.

Reads AindOtelSettings from clabe.yml. When enabled, the SDK is configured before the span opens (so @runnable app spans nest under it) and the OTLP log bridge is attached. The run's attribute bag is seeded from the profile's config-and-defaults (initial_attributes) before the root span starts, so the root span and every child carry it. Telemetry is best effort — a missing SDK or bad config is logged and the run proceeds untraced. The span is ended and exported on exit, before the caller's cleanup, so a caller that then blocks (or is killed) cannot strand it; an atexit fallback covers orderly interpreter teardown that skips this finally without replacing the host application's signal handlers.

Parameters:

Name Type Description Default
launcher Launcher

The launcher being instrumented.

required
experiment_name str | None

Name of the workflow being run, used when run_name is not set in config.

None

Yields:

Type Description
Span

The root span for the run.

Source code in src/clabe/logging/otel/__init__.py
@contextlib.contextmanager
def run_span(launcher: "Launcher", experiment_name: str | None = None) -> Generator[Span, None, None]:
    """Instrument a launcher run: install telemetry if enabled, then open the root span.

    Reads `AindOtelSettings` from clabe.yml. When enabled, the SDK is configured
    before the span opens (so ``@runnable`` app spans nest under it) and the OTLP log bridge
    is attached. The run's attribute bag is seeded from the profile's config-and-defaults
    ([`initial_attributes`][clabe.logging.otel._settings.OtelSettings.initial_attributes]) before the root span
    starts, so the root span and every child carry it. Telemetry is best effort — a missing
    SDK or bad config is logged and the run proceeds untraced. The span is ended and exported
    on exit, before the caller's cleanup, so a caller that then blocks (or is killed) cannot
    strand it; an ``atexit`` fallback covers orderly interpreter teardown that skips this
    ``finally`` without replacing the host application's signal handlers.

    Args:
        launcher: The launcher being instrumented.
        experiment_name: Name of the workflow being run, used when
            `run_name` is not set in config.

    Yields:
        The root span for the run.
    """
    global _active_span, _active_settings
    telemetry_configured = False
    try:
        settings: OtelSettings | None = AindOtelSettings()
    except Exception:  # observability must never break a run
        logger.warning("Failed to load otel settings; telemetry disabled", exc_info=True)
        settings = None

    if settings is not None and settings.enabled:
        try:
            from ._setup import configure

            configure(settings)
            set_attributes(settings.initial_attributes())
            telemetry_configured = True
        except Exception:  # observability must never break a run
            logger.warning("Failed to set up telemetry; continuing without it", exc_info=True)

    span_name = (settings.run_name if settings is not None else None) or experiment_name or "experiment"
    root = _tracer.start_span(span_name)
    _active_span, _active_settings = root, settings
    if telemetry_configured:
        _install_atexit_fallback()
    try:
        with trace.use_span(root, end_on_exit=False):
            yield root
    finally:
        # The atexit fallback clears the active span when it closes one, so this tells us whether
        # it got there first and the span is already ended and exported.
        closed_by_atexit = _active_span is not root
        _active_span, _active_settings = None, None
        set_attributes({})
        if not closed_by_atexit:
            root.end()
            # Drain before returning: the root span has just ended and is still queued, and
            # the caller may block (or be killed) before the next batch would have gone out.
            flush()

bind_session

bind_session(session: Session) -> None

Enrich the active run with the session identity, as soon as it is registered.

Called by the launcher from register_session, this is the first point the session (subject, experimenter, ...) is known — stage 3 of attribute population. A no-op outside a run or when telemetry is off.

Parameters:

Name Type Description Default
session Session

The session model just registered with the launcher.

required
Source code in src/clabe/logging/otel/__init__.py
def bind_session(session: "Session") -> None:
    """Enrich the active run with the session identity, as soon as it is registered.

    Called by the launcher from [`register_session`][clabe.launcher.Launcher.register_session], this is
    the first point the session (subject, experimenter, ...) is known — stage 3 of attribute
    population. A no-op outside a run or when telemetry is off.

    Args:
        session: The session model just registered with the launcher.
    """
    if _active_span is None or _active_settings is None:
        return
    try:
        _enrich(_active_settings.session_attributes(session))
    except Exception:  # observability must never break a run
        logger.warning("Failed to bind session identity to telemetry", exc_info=True)

enrich_attribute

enrich_attribute(name: str, value: AttributeValue) -> None

Set or override a single telemetry attribute at any point during a run.

Stage 4 of attribute population: the escape hatch for values that have no dedicated config field (e.g. instrument_id) or that become known mid-run. The attribute is added to the run's bag — so it appears on every subsequent span and log — and stamped on the currently open root span immediately. A no-op outside a run or when telemetry is off.

Parameters:

Name Type Description Default
name str

The attribute key, emitted verbatim (use log-schema snake_case, e.g. rig_id).

required
value AttributeValue

The attribute value.

required
Source code in src/clabe/logging/otel/__init__.py
def enrich_attribute(name: str, value: AttributeValue) -> None:
    """Set or override a single telemetry attribute at any point during a run.

    Stage 4 of attribute population: the escape hatch for values that have no dedicated
    config field (e.g. ``instrument_id``) or that become known mid-run. The attribute is
    added to the run's bag — so it appears on every subsequent span and log — and stamped on
    the currently open root span immediately. A no-op outside a run or when telemetry is off.

    Args:
        name: The attribute key, emitted verbatim (use log-schema snake_case, e.g. ``rig_id``).
        value: The attribute value.
    """
    if _active_span is None:
        return
    _enrich({name: value})