Skip to content

logging - Context-based logging

Overview

firebird.base.logging

This module provides context-based logging system built on top of standard logging module. It also solves the common logging management problem when various modules use hard-coded separate loggers, and provides several types of message wrappers that allow lazy message interpolation using f-string, brace (str.format) or dollar (string.Template) formats.

The context-based logging:

  1. Adds context information into logging.LogRecord, that could be used in logging entry formats.
  2. Allows assignment of loggers to specific contexts.

This module also provides message wrapper classes (FStrMessage, BraceMessage, DollarMessage) that defer string formatting until the log record is actually processed by a handler. This avoids the performance cost of formatting messages that might be filtered out due to log levels.

Basics

Normally, when you want to use a logger, you call the logging.getLogger function and pass it a logger name (or not to get the root logger). The common (and recommended) practice is to use getLogger(__name__) which often leads to logging configuration problems as complex applications with many modules (including used libraries) may create complex logger hierarchy.

Our logging module solves the problem by replacing the logger name with agent identification. The agent is typically an unit of code that works in specific execution contexts. For example a code that process client request in web application (where request is the context), or executes SQL command (the context could be a database connection). In most cases, the agent is an instance of some class.

So, from user's perspective, the context logging is used similarly to normal Python logging - but you pass the agent identification instead logger name to get_logger function. If agent identification is a string, it's used as is. If it's an object, it uses value of its _agent_name_ attribute if defined, otherwise it uses name in "MODULE_NAME.CLASS_QUALNAME" format. If _agent_name_ value is not a string, it's converted to string.

The typical usage pattern inside a class is therefore:

logger = get_logger(self)

or for direct use:

get_logger(self).debug("message")

The get_logger also has an optional topic string parameter that could be used to differentiate between various logging "streams". For example the firebird.base.trace module uses context logging with topic "trace", so it's possible to configure the logging system to handle "trace" output in specific way.

The underlying machinery behind get_logger function maps the agent and its context to particular logging.Logger, and returns a firebird.base.logging.ContextLoggerAdapter that you can use as normal logger. This adapter is responsible to add context information into logging.LogRecord.

Context information

The context information added by ContextLoggerAdapter into logging.LogRecord consists from next items:

  • agent: String representation of the agent identification described above.
  • context: Agent context that could be defined via log_context attribute on agent instance, or by assigning its value directly to extra['context'] on adapter returned by get_logger() function.
  • domain: A name assigned to a group of agents (more about that later).
  • topic: Name of a logging stream.

The adapter keeps context in its extra dictionary. When processing a log message, it copies agent.log_context into extra['context'] only if that key is absent (using None when the agent has no log_context attribute). Once set, the value remains in the adapter; later changes to agent.log_context do not overwrite it. You can set or change log.extra['context'] yourself at any time, including before the first log message.

To have the adapter read agent.log_context again on its next log message, delete the cached key:

log = get_logger(agent)  # An existing agent object
log.extra['context'] = 'manual context'
log.info('Uses the manual context')

agent.log_context = 'current request'
del log.extra['context']
log.info('Uses the current request context')

These record fields can be used in logging.Formatter templates. If you want to combine normal and context logging, assign ContextFilter to your logging.Handler to add (empty) context information into LogRecords that are produced by normal loggers.

LoggingManager

The firebird.base.logging module defines a global LoggingManager instance logging_manager that manages several mappings and implements the LoggingManager.get_logger method.

Some methods are also provided as global functions for conveniense: get_logger, set_agent_mapping, set_domain_mapping and get_agent_name.

Mappings and Logger names

The logging.Logger wrapped by the get_logger function is determined by applying the values ​​of several parameters to the logger name format. These parameters are:

  • Domain: String used to group output from agents.
  • Topic: String identification of particular logging stream.

The logger name format is a list that can contain any number of string values and at most one occurrence of DOMAIN or TOPIC enum values. Empty strings are removed.

The final logging.Logger name is constructed by joining elements of this list with dots, and with sentinels replaced with domain and topic names.

For example, if values are defined as:

logger_fmt = ['app', DOMAIN, TOPIC]
domain = 'database'
topic = 'trace'

the Logger name will be: "app.database.trace"

The logger name format is defined in LoggingManager.logger_fmt property, and it's an empty list by default, which means that get_logger function always maps to root logger.

The domain is determined from agent passed to get_logger. You can use set_domain_mapping to assign agent identifications to particular domain. The agents that are not assigned to domain belong to default domain specifid in LoggingManager.default_domain, which is None by default.

It's also possible to change agent identification used for logger name mapping porposes to different value with set_agent_mapping function.

Lazy Formatting Messages

This module also provides message wrapper classes (FStrMessage, BraceMessage, DollarMessage) that defer string formatting until the log record is actually processed by a handler. This avoids the performance cost of formatting messages that might be filtered out due to log levels.

Basic Setup Example

import logging
from firebird.base.logging import (
    get_logger, LogLevel, ContextFilter, logging_manager,
    DOMAIN, TOPIC # For logger_fmt
)

# 1. Configure standard logging (handlers, formatters)
log_format = "[%(levelname)-8s] %(asctime)s %(name)s (%(agent)s) - %(message)s"
formatter = logging.Formatter(log_format)
handler = logging.StreamHandler()
handler.setFormatter(formatter)

# 2. Add ContextFilter to handler(s) to ensure context fields exist
handler.addFilter(ContextFilter())

# 3. Get the root logger or specific standard loggers and add the handler
root_logger = logging.getLogger()
root_logger.addHandler(handler)
root_logger.setLevel(LogLevel.DEBUG) # Use LogLevel enum or logging constants

# 4. (Optional) Configure logging_manager mappings
logging_manager.logger_fmt = ['app', DOMAIN, TOPIC] # Logger name format
logging_manager.default_domain = 'web'            # Default domain if not mapped
logging_manager.set_domain_mapping('db', ['myapp.database.Connection']) # Map agent to domain

# 5. Use in your code
class RequestHandler:
    _agent_name_ = 'myapp.web.RequestHandler' # Optional explicit agent name
    log_context = None # Can be set per request, e.g., client IP

    def handle(self, request_id):
        self.log_context = f"ReqID:{request_id}"
        logger = get_logger(self, topic='requests') # Get context logger
        logger.info("Handling request...")
        # ... processing ...
        logger.debug("Request handled successfully.")

class DbConnection:
    _agent_name_ = 'myapp.database.Connection'
    log_context = None # e.g., DB user

    def query(self, sql):
        self.log_context = "user:admin"
        logger = get_logger(self) # Use default topic (None)
        logger.debug("Executing query: %s", sql) # Standard formatting works too
        # ... execute ...

# --- Execution ---
handler_instance = RequestHandler()
db_conn = DbConnection()

handler_instance.handle("12345")
db_conn.query("SELECT * FROM T")

# --- Example Output ---
# [INFO    ] 2023-10-27... app.web.requests (myapp.web.RequestHandler) - Handling request...
# [DEBUG   ] 2023-10-27... app.web.requests (myapp.web.RequestHandler) - Request handled successfully.
# [DEBUG   ] 2023-10-27... app.db (myapp.database.Connection) - Executing query: SELECT * FROM T

Enums & Flags

firebird.base.logging.FormatElement

Bases: Enum

Sentinels used within LoggingManager.logger_fmt list.

Source code in firebird/base/logging.py
class FormatElement(Enum):
    """Sentinels used within `LoggingManager.logger_fmt` list."""
    DOMAIN = 1
    TOPIC = 2

firebird.base.logging.LogLevel

Bases: IntEnum

Mirrors standard logging levels for convenience and type hinting.

Provides symbolic names (e.g., LogLevel.DEBUG) corresponding to the integer values used by the standard logging module (logging.DEBUG).

Source code in firebird/base/logging.py
class LogLevel(IntEnum):
    """Mirrors standard `logging` levels for convenience and type hinting.

    Provides symbolic names (e.g., `LogLevel.DEBUG`) corresponding to the
    integer values used by the standard `logging` module (`logging.DEBUG`).
    """
    NOTSET = 0
    DEBUG = 10
    INFO = 20
    WARNING = 30
    ERROR = 40
    CRITICAL = 50
    FATAL = CRITICAL
    WARN = WARNING

Constants

firebird.base.logging.DOMAIN: FormatElement module-attribute

Sentinel representing the domain element in LoggingManager.logger_fmt.

firebird.base.logging.TOPIC: FormatElement module-attribute

Sentinel representing the topic element in LoggingManager.logger_fmt.

Functions

firebird.base.logging.get_logger module-attribute

Shortcut to global LoggingManager.get_logger function.

firebird.base.logging.set_domain_mapping module-attribute

Shortcut to global LoggingManager.set_domain_mapping function.

firebird.base.logging.set_agent_mapping module-attribute

Shortcut to global LoggingManager.set_agent_mapping function.

firebird.base.logging.get_agent_name module-attribute

Shortcut to global LoggingManager.get_agent_name function.

Adapters and Filters

firebird.base.logging.ContextLoggerAdapter

Bases: LoggerAdapter

Logger adapter injecting context (domain, topic, agent, context) info.

Wraps a standard logging.Logger. When a logging method (e.g., info, debug) is called, it adds the context information into the extra dictionary, making it available as attributes on the resulting logging.LogRecord.

Parameters:

Name Type Description Default
logger

The standard logging.Logger instance to wrap.

required
domain str | None

Context Domain name (or None).

required
topic str | None

Context Topic name (or None).

required
agent Any

The original agent object or string passed to get_logger.

required
agent_name str

The resolved string name for the agent.

required
Source code in firebird/base/logging.py
class ContextLoggerAdapter(logging.LoggerAdapter):
    """Logger adapter injecting context (`domain`, `topic`, `agent`, `context`) info.

    Wraps a standard [logging.Logger][]. When a logging method (e.g., `info`, `debug`)
    is called, it adds the context information into the `extra` dictionary, making
    it available as attributes on the resulting [logging.LogRecord][].

    Parameters:
        logger: The standard `logging.Logger` instance to wrap.
        domain: Context Domain name (or None).
        topic: Context Topic name (or None).
        agent: The original agent object or string passed to `get_logger`.
        agent_name: The resolved string name for the agent.
    """
    def __init__(self, logger, domain: str | None, topic: str | None, agent: Any, agent_name: str):
        self.agent = agent
        super().__init__(logger,
                         {'domain': domain,
                          'topic': topic,
                          'agent': agent_name}
                         )
    def process(self, msg: Any, kwargs: dict[str, Any]) -> tuple[Any, dict[str, Any]]:
        """Process the logging message and keyword arguments passed in to
        a logging call to insert contextual information.

        - Ensures `self.extra` contains `domain`, `topic`, and `agent` (from init).
        - Adds `context` to `self.extra`, taking it from `self.agent.log_context`
          if available, otherwise `None`.
        - Merges the adapter's `extra` dictionary with any `extra` dictionary
          passed in `kwargs`, giving precedence to keys in `kwargs['extra']`.
        - Stores the final merged `extra` dictionary into `kwargs['extra']`.

        Returns:
            The possibly modified `msg` and `kwargs`.
        """
        if 'context' not in self.extra:
            self.extra['context'] = getattr(self.agent, 'log_context', None)
        #if "stacklevel" not in kwargs:
            #kwargs["stacklevel"] = 1
        kwargs['extra'] = dict(self.extra, **kwargs['extra']) if 'extra' in kwargs else self.extra
        return msg, kwargs

process(msg: Any, kwargs: dict[str, Any]) -> tuple[Any, dict[str, Any]]

Process the logging message and keyword arguments passed in to a logging call to insert contextual information.

  • Ensures self.extra contains domain, topic, and agent (from init).
  • Adds context to self.extra, taking it from self.agent.log_context if available, otherwise None.
  • Merges the adapter's extra dictionary with any extra dictionary passed in kwargs, giving precedence to keys in kwargs['extra'].
  • Stores the final merged extra dictionary into kwargs['extra'].

Returns:

Type Description
tuple[Any, dict[str, Any]]

The possibly modified msg and kwargs.

Source code in firebird/base/logging.py
def process(self, msg: Any, kwargs: dict[str, Any]) -> tuple[Any, dict[str, Any]]:
    """Process the logging message and keyword arguments passed in to
    a logging call to insert contextual information.

    - Ensures `self.extra` contains `domain`, `topic`, and `agent` (from init).
    - Adds `context` to `self.extra`, taking it from `self.agent.log_context`
      if available, otherwise `None`.
    - Merges the adapter's `extra` dictionary with any `extra` dictionary
      passed in `kwargs`, giving precedence to keys in `kwargs['extra']`.
    - Stores the final merged `extra` dictionary into `kwargs['extra']`.

    Returns:
        The possibly modified `msg` and `kwargs`.
    """
    if 'context' not in self.extra:
        self.extra['context'] = getattr(self.agent, 'log_context', None)
    #if "stacklevel" not in kwargs:
        #kwargs["stacklevel"] = 1
    kwargs['extra'] = dict(self.extra, **kwargs['extra']) if 'extra' in kwargs else self.extra
    return msg, kwargs

firebird.base.logging.ContextFilter

Bases: Filter

Logging filter ensuring context fields exist on LogRecord instances.

Checks for domain, topic, agent, and context attributes on each log record. If any are missing (e.g., for records from standard loggers not using ContextLoggerAdapter), it adds them with a value of None.

Usage

Attach an instance of this filter to logging.Handler objects to ensure formatters expecting these fields do not raise AttributeError.

Example
handler = logging.StreamHandler()
handler.addFilter(ContextFilter())
# ... add handler to logger ...
Source code in firebird/base/logging.py
class ContextFilter(logging.Filter):
    """Logging filter ensuring context fields exist on `LogRecord` instances.

    Checks for `domain`, `topic`, `agent`, and `context` attributes on each
    log record. If any are missing (e.g., for records from standard loggers
    not using `ContextLoggerAdapter`), it adds them with a value of `None`.

    Usage:
        Attach an instance of this filter to `logging.Handler` objects to ensure
        formatters expecting these fields do not raise `AttributeError`.

    Example:
        ```python
        handler = logging.StreamHandler()
        handler.addFilter(ContextFilter())
        # ... add handler to logger ...
        ```
    """
    def filter(self, record) -> bool:
        for attr in ('domain', 'topic', 'agent', 'context'):
            if not hasattr(record, attr):
                setattr(record, attr, None)
        return True

Logging manager

firebird.base.logging.LoggingManager

Logging manager.

Source code in firebird/base/logging.py
class LoggingManager:
    """Logging manager.
    """
    def __init__(self):
        self._agent_domain_map: dict[str, str] = {}
        self._domain_agent_map: dict[str, set] = {}
        self._topic_map: dict[str, str] = {}
        self._agent_map: dict[str, str] = {}
        self.__logger_fmt: list[str | FormatElement] = []
        self.__default_domain: str | None = None
        self._logger_factory: Callable = logging.getLogger
    def get_logger_factory(self) -> Callable:
        """Return a callable which is used to create a Logger.
        """
        return self._logger_factory
    def set_logger_factory(self, factory) -> None:
        """Set a callable which is used to create a Logger.

        Parameters:
            factory: The factory callable to be used to instantiate a logger.

        The factory has the following signature: `factory(name, *args, **kwargs)`
        """
        self._logger_factory = factory
    def reset(self) -> None:
        """Resets manager to "factory defaults": no mappings, no `logger_fmt` and undefined
        `default_domain`.
        """
        self._agent_domain_map.clear()
        self._domain_agent_map.clear()
        self._topic_map.clear()
        self._agent_map.clear()
        self.__logger_fmt.clear()
        self.__default_domain = None
    @property
    def logger_fmt(self) -> list[str | FormatElement]:
        """Logger format.

        The list can contain any number of string values and at most one occurrence of `DOMAIN`
        or `TOPIC` enum values. Empty strings are removed.

        The final `logging.Logger` name is constructed by joining elements of this list with
        dots, and with sentinels replaced with `domain` and `topic` names.

        Example:
           ```python
           logger_fmt = ['app', DOMAIN, TOPIC]
           domain = 'database'
           topic = 'trace'

           Logger name will be: "app.database.trace"
           ```
        """
        return self.__logger_fmt
    @logger_fmt.setter
    def logger_fmt(self, value: list[str | FormatElement]) -> None:
        """Sets the logger name format list.

        Validates the list to ensure it contains only non-empty strings and
        at most one `DOMAIN` and one `TOPIC` sentinel.

        :param value: The list defining the logger name format.
        :raises ValueError: If the format list is invalid (e.g., multiple DOMAINs).
        """
        def validated(seq):
            domain_found = False
            topic_found = False
            for item in seq:
                match item:
                    case x if isinstance(x, str):
                        if x:
                            yield item
                    case FormatElement.DOMAIN:
                        if domain_found:
                            raise ValueError("Only one occurence of sentinel DOMAIN allowed")
                        domain_found = True
                        yield item
                    case FormatElement.TOPIC:
                        if topic_found:
                            raise ValueError("Only one occurence of sentinel TOPIC allowed")
                        topic_found = True
                        yield item
                    case _:
                        raise ValueError(f"Unsupported item type {type(item)}")

        self.__logger_fmt = list(validated(value))
    @property
    def default_domain(self) -> str | None:
        """Default domain. Could be either a string or `None`.

        Important:
            When assigned, it does not validate the value type, but converts it to string.
        """
        return self.__default_domain
    @default_domain.setter
    def default_domain(self, value: str | None) -> None:
        self.__default_domain = None if value is None else str(value)
    def _get_logger_name(self, domain: str | None, topic: str | None) -> str:
        """Returns `logging.Logger` name.
        """
        result = []
        for item in self.logger_fmt:
            match item:
                case x if isinstance(x, str):
                    result.append(item)
                case x if x is DOMAIN:
                    if domain:
                        result.append(domain)
                case x if x is TOPIC:
                    if topic:
                        result.append(topic)
        return '.'.join(result)
    def set_topic_mapping(self, topic: str, new_topic: str | None) -> None:
        """Sets or removes the mapping of an topic name to another name.

        Arguments:
            topic: Topic name.
            new_topic: Either `None` or new topic name.

        - When `new_topic` is a string, it maps `topic` to `new_topic`. Empty string is
          like `None`.
        - When `new_topic` is `None`, it removes any mapping.

        Important:
            Does not validate the `new_topic` value type, instead it's converted to string.
        """
        if new_topic:
            self._topic_map[topic] = str(new_topic)
        else:
            self._topic_map.pop(topic, None)
    def get_topic_mapping(self, topic: str) -> str | None:
        """Returns current name mapping for topic.

        Arguments:
            topic: Topic name.

        Returns:
            Reassigned topic name or `None`.
        """
        return self._topic_map.get(topic)
    def get_agent_name(self, agent: Any) -> str:
        """Determine the canonical string name for a given agent identifier.

        Parameters:
            agent: Agent identifier (string, or object).

        Returns:
            The resolved agent name (string).

        Logic:

        1. If `agent` is a string, it's used directly.
        2. If `agent` is an object:
           - Uses `agent._agent_name_` if defined (converting to string if needed).
           - Otherwise, constructs name as `module.ClassQualname`.
        3. Applies any agent name mapping defined via `set_agent_mapping` to the
           name determined in steps 1 or 2.
        4. Ensures the final result is a string.

        Example:
            ```
            > from firebird.base.logging import logging_manager
            > logging_manager.get_agent_name(logging_manager)
            'firebird.base.logging.LoggingManager'
            ```
        """
        agent_name: Any = agent
        if not isinstance(agent, str):
            if not (agent_name := getattr(agent, '_agent_name_', None)):
                agent_name = f'{agent.__class__.__module__}.{agent.__class__.__qualname__}'
        agent_name = self._agent_map.get(agent_name, agent_name)
        return str(agent_name)
    def set_agent_mapping(self, agent: str, new_agent: str | None) -> None:
        """Sets or removes the mapping of an agent name to another name.

        Parameters:
            agent: Agent name.
            new_agent: New agent name or `None` to remove the mapping. Empty string is like `None`.

        Important:
            Does not validate the `new_agent` value type, instead it's converted to string.
        """
        if new_agent:
            self._agent_map[agent] = str(new_agent)
        else:
            self._agent_map.pop(agent, None)
    def get_agent_mapping(self, agent: str) -> str | None:
        """Returns current name mapping for agent.

        Arguments:
            agent: Agent name.

        Returns:
            Reassigned agent name or `None`.
        """
        return self._agent_map.get(agent)
    def get_agent_domain(self, agent: str) -> str | None:
        """Returns domain name assigned to agent.

        Arguments:
            agent: Agent name.

        Returns:
            Domain assigned to agent or `None`.
        """
        return self._agent_domain_map.get(agent)
    def set_domain_mapping(self, domain: str, agents: Iterable[str] | str | None, *,
                           replace: bool=False) -> None:
        """Sets, updates, or removes agent name mappings to a domain.

        Parameters:
            domain:  Domain name.
            agents:  Iterable with agent names, single agent name, or `None`.
            replace: When True, the new mapping replaces the current one, otherwise the mapping is updated.

        Important:
            Passing `None` to `agents` removes all agent mappings for specified domain,
            regardless of `replace` value.
        """
        # Remove agents that are already mapped
        if agents is not None:
            for agent in set([agents] if isinstance(agents, str) else agents):
                current_domain = self._agent_domain_map.pop(agent, None)
                if current_domain:
                    self._domain_agent_map[current_domain].discard(agent)
                    if not self._domain_agent_map[current_domain]:
                        del self._domain_agent_map[current_domain]
        if (replace or agents is None) and domain in self._domain_agent_map:
            for agent in self._domain_agent_map[domain]:
                del self._agent_domain_map[agent]
            if agents is None:
                del self._domain_agent_map[domain]
                return
        if replace or domain not in self._domain_agent_map:
            self._domain_agent_map[domain] = set()
        agents = set([agents] if isinstance(agents, str) else agents)
        self._domain_agent_map[domain].update(agents)
        for agent in agents:
            self._agent_domain_map[agent] = domain
    def get_domain_mapping(self, domain: str) -> set[str] | None:
        """Returns current agent mapping for domain.

        Arguments:
            domain: Domain name.

        Returns:
            Set of agent names assigned to domain or `None`.
        """
        return self._domain_agent_map.get(domain)
    def get_logger(self, agent: Any, topic: str | None=None) -> ContextLoggerAdapter:
        """Get a ContextLoggerAdapter configured for the specified agent and topic.

        This is the primary function for obtaining a logger in the context logging system.
        It determines the appropriate underlying `logging.Logger` based on the agent's
        domain and the topic, then wraps it in a `ContextLoggerAdapter` to inject
        context information.

        Arguments:
            agent: The agent identifier (object or string). Used to determine the
                   `agent_name` and `domain`.
            topic: Optional topic string for the logging stream (e.g., 'network', 'db').

        Returns:
            A `ContextLoggerAdapter` instance ready for logging.

        Process Flow:

        1. Determine `agent_name` using `get_agent_name(agent)`.
        2. Determine `domain` by looking up `agent_name` in the domain mapping,
           falling back to `self.default_domain`.
        3. Apply topic mapping to the input `topic` (if any).
        4. Construct the final underlying `logging.Logger` name using `self.logger_fmt`,
           substituting the determined `domain` and mapped `topic`.
        5. Get/create the `logging.Logger` instance using `self._logger_factory`
           with the constructed name.
        6. Create and return a `ContextLoggerAdapter` wrapping the logger and
           carrying the `domain`, mapped `topic`, original `agent`, and `agent_name`.
        """
        agent_name = self.get_agent_name(agent)
        agent_name = self._agent_map.get(agent_name, agent_name)
        domain = self._agent_domain_map.get(agent_name, self.default_domain)
        topic = self._topic_map.get(topic, topic)
        # Get logger
        logger = self._logger_factory(self._get_logger_name(domain, topic))
        return ContextLoggerAdapter(logger, domain, topic, agent, agent_name)

default_domain: str | None property writable

Default domain. Could be either a string or None.

Important

When assigned, it does not validate the value type, but converts it to string.

logger_fmt: list[str | FormatElement] property writable

Logger format.

The list can contain any number of string values and at most one occurrence of DOMAIN or TOPIC enum values. Empty strings are removed.

The final logging.Logger name is constructed by joining elements of this list with dots, and with sentinels replaced with domain and topic names.

Example
logger_fmt = ['app', DOMAIN, TOPIC]
domain = 'database'
topic = 'trace'

Logger name will be: "app.database.trace"

get_agent_domain(agent: str) -> str | None

Returns domain name assigned to agent.

Parameters:

Name Type Description Default
agent str

Agent name.

required

Returns:

Type Description
str | None

Domain assigned to agent or None.

Source code in firebird/base/logging.py
def get_agent_domain(self, agent: str) -> str | None:
    """Returns domain name assigned to agent.

    Arguments:
        agent: Agent name.

    Returns:
        Domain assigned to agent or `None`.
    """
    return self._agent_domain_map.get(agent)

get_agent_mapping(agent: str) -> str | None

Returns current name mapping for agent.

Parameters:

Name Type Description Default
agent str

Agent name.

required

Returns:

Type Description
str | None

Reassigned agent name or None.

Source code in firebird/base/logging.py
def get_agent_mapping(self, agent: str) -> str | None:
    """Returns current name mapping for agent.

    Arguments:
        agent: Agent name.

    Returns:
        Reassigned agent name or `None`.
    """
    return self._agent_map.get(agent)

get_agent_name(agent: Any) -> str

Determine the canonical string name for a given agent identifier.

Parameters:

Name Type Description Default
agent Any

Agent identifier (string, or object).

required

Returns:

Type Description
str

The resolved agent name (string).

Logic:

  1. If agent is a string, it's used directly.
  2. If agent is an object:
  3. Uses agent._agent_name_ if defined (converting to string if needed).
  4. Otherwise, constructs name as module.ClassQualname.
  5. Applies any agent name mapping defined via set_agent_mapping to the name determined in steps 1 or 2.
  6. Ensures the final result is a string.
Example
> from firebird.base.logging import logging_manager
> logging_manager.get_agent_name(logging_manager)
'firebird.base.logging.LoggingManager'
Source code in firebird/base/logging.py
def get_agent_name(self, agent: Any) -> str:
    """Determine the canonical string name for a given agent identifier.

    Parameters:
        agent: Agent identifier (string, or object).

    Returns:
        The resolved agent name (string).

    Logic:

    1. If `agent` is a string, it's used directly.
    2. If `agent` is an object:
       - Uses `agent._agent_name_` if defined (converting to string if needed).
       - Otherwise, constructs name as `module.ClassQualname`.
    3. Applies any agent name mapping defined via `set_agent_mapping` to the
       name determined in steps 1 or 2.
    4. Ensures the final result is a string.

    Example:
        ```
        > from firebird.base.logging import logging_manager
        > logging_manager.get_agent_name(logging_manager)
        'firebird.base.logging.LoggingManager'
        ```
    """
    agent_name: Any = agent
    if not isinstance(agent, str):
        if not (agent_name := getattr(agent, '_agent_name_', None)):
            agent_name = f'{agent.__class__.__module__}.{agent.__class__.__qualname__}'
    agent_name = self._agent_map.get(agent_name, agent_name)
    return str(agent_name)

get_domain_mapping(domain: str) -> set[str] | None

Returns current agent mapping for domain.

Parameters:

Name Type Description Default
domain str

Domain name.

required

Returns:

Type Description
set[str] | None

Set of agent names assigned to domain or None.

Source code in firebird/base/logging.py
def get_domain_mapping(self, domain: str) -> set[str] | None:
    """Returns current agent mapping for domain.

    Arguments:
        domain: Domain name.

    Returns:
        Set of agent names assigned to domain or `None`.
    """
    return self._domain_agent_map.get(domain)

get_logger(agent: Any, topic: str | None = None) -> ContextLoggerAdapter

Get a ContextLoggerAdapter configured for the specified agent and topic.

This is the primary function for obtaining a logger in the context logging system. It determines the appropriate underlying logging.Logger based on the agent's domain and the topic, then wraps it in a ContextLoggerAdapter to inject context information.

Parameters:

Name Type Description Default
agent Any

The agent identifier (object or string). Used to determine the agent_name and domain.

required
topic str | None

Optional topic string for the logging stream (e.g., 'network', 'db').

None

Returns:

Type Description
ContextLoggerAdapter

A ContextLoggerAdapter instance ready for logging.

Process Flow:

  1. Determine agent_name using get_agent_name(agent).
  2. Determine domain by looking up agent_name in the domain mapping, falling back to self.default_domain.
  3. Apply topic mapping to the input topic (if any).
  4. Construct the final underlying logging.Logger name using self.logger_fmt, substituting the determined domain and mapped topic.
  5. Get/create the logging.Logger instance using self._logger_factory with the constructed name.
  6. Create and return a ContextLoggerAdapter wrapping the logger and carrying the domain, mapped topic, original agent, and agent_name.
Source code in firebird/base/logging.py
def get_logger(self, agent: Any, topic: str | None=None) -> ContextLoggerAdapter:
    """Get a ContextLoggerAdapter configured for the specified agent and topic.

    This is the primary function for obtaining a logger in the context logging system.
    It determines the appropriate underlying `logging.Logger` based on the agent's
    domain and the topic, then wraps it in a `ContextLoggerAdapter` to inject
    context information.

    Arguments:
        agent: The agent identifier (object or string). Used to determine the
               `agent_name` and `domain`.
        topic: Optional topic string for the logging stream (e.g., 'network', 'db').

    Returns:
        A `ContextLoggerAdapter` instance ready for logging.

    Process Flow:

    1. Determine `agent_name` using `get_agent_name(agent)`.
    2. Determine `domain` by looking up `agent_name` in the domain mapping,
       falling back to `self.default_domain`.
    3. Apply topic mapping to the input `topic` (if any).
    4. Construct the final underlying `logging.Logger` name using `self.logger_fmt`,
       substituting the determined `domain` and mapped `topic`.
    5. Get/create the `logging.Logger` instance using `self._logger_factory`
       with the constructed name.
    6. Create and return a `ContextLoggerAdapter` wrapping the logger and
       carrying the `domain`, mapped `topic`, original `agent`, and `agent_name`.
    """
    agent_name = self.get_agent_name(agent)
    agent_name = self._agent_map.get(agent_name, agent_name)
    domain = self._agent_domain_map.get(agent_name, self.default_domain)
    topic = self._topic_map.get(topic, topic)
    # Get logger
    logger = self._logger_factory(self._get_logger_name(domain, topic))
    return ContextLoggerAdapter(logger, domain, topic, agent, agent_name)

get_logger_factory() -> Callable

Return a callable which is used to create a Logger.

Source code in firebird/base/logging.py
def get_logger_factory(self) -> Callable:
    """Return a callable which is used to create a Logger.
    """
    return self._logger_factory

get_topic_mapping(topic: str) -> str | None

Returns current name mapping for topic.

Parameters:

Name Type Description Default
topic str

Topic name.

required

Returns:

Type Description
str | None

Reassigned topic name or None.

Source code in firebird/base/logging.py
def get_topic_mapping(self, topic: str) -> str | None:
    """Returns current name mapping for topic.

    Arguments:
        topic: Topic name.

    Returns:
        Reassigned topic name or `None`.
    """
    return self._topic_map.get(topic)

reset() -> None

Resets manager to "factory defaults": no mappings, no logger_fmt and undefined default_domain.

Source code in firebird/base/logging.py
def reset(self) -> None:
    """Resets manager to "factory defaults": no mappings, no `logger_fmt` and undefined
    `default_domain`.
    """
    self._agent_domain_map.clear()
    self._domain_agent_map.clear()
    self._topic_map.clear()
    self._agent_map.clear()
    self.__logger_fmt.clear()
    self.__default_domain = None

set_agent_mapping(agent: str, new_agent: str | None) -> None

Sets or removes the mapping of an agent name to another name.

Parameters:

Name Type Description Default
agent str

Agent name.

required
new_agent str | None

New agent name or None to remove the mapping. Empty string is like None.

required
Important

Does not validate the new_agent value type, instead it's converted to string.

Source code in firebird/base/logging.py
def set_agent_mapping(self, agent: str, new_agent: str | None) -> None:
    """Sets or removes the mapping of an agent name to another name.

    Parameters:
        agent: Agent name.
        new_agent: New agent name or `None` to remove the mapping. Empty string is like `None`.

    Important:
        Does not validate the `new_agent` value type, instead it's converted to string.
    """
    if new_agent:
        self._agent_map[agent] = str(new_agent)
    else:
        self._agent_map.pop(agent, None)

set_domain_mapping(domain: str, agents: Iterable[str] | str | None, *, replace: bool = False) -> None

Sets, updates, or removes agent name mappings to a domain.

Parameters:

Name Type Description Default
domain str

Domain name.

required
agents Iterable[str] | str | None

Iterable with agent names, single agent name, or None.

required
replace bool

When True, the new mapping replaces the current one, otherwise the mapping is updated.

False
Important

Passing None to agents removes all agent mappings for specified domain, regardless of replace value.

Source code in firebird/base/logging.py
def set_domain_mapping(self, domain: str, agents: Iterable[str] | str | None, *,
                       replace: bool=False) -> None:
    """Sets, updates, or removes agent name mappings to a domain.

    Parameters:
        domain:  Domain name.
        agents:  Iterable with agent names, single agent name, or `None`.
        replace: When True, the new mapping replaces the current one, otherwise the mapping is updated.

    Important:
        Passing `None` to `agents` removes all agent mappings for specified domain,
        regardless of `replace` value.
    """
    # Remove agents that are already mapped
    if agents is not None:
        for agent in set([agents] if isinstance(agents, str) else agents):
            current_domain = self._agent_domain_map.pop(agent, None)
            if current_domain:
                self._domain_agent_map[current_domain].discard(agent)
                if not self._domain_agent_map[current_domain]:
                    del self._domain_agent_map[current_domain]
    if (replace or agents is None) and domain in self._domain_agent_map:
        for agent in self._domain_agent_map[domain]:
            del self._agent_domain_map[agent]
        if agents is None:
            del self._domain_agent_map[domain]
            return
    if replace or domain not in self._domain_agent_map:
        self._domain_agent_map[domain] = set()
    agents = set([agents] if isinstance(agents, str) else agents)
    self._domain_agent_map[domain].update(agents)
    for agent in agents:
        self._agent_domain_map[agent] = domain

set_logger_factory(factory) -> None

Set a callable which is used to create a Logger.

Parameters:

Name Type Description Default
factory

The factory callable to be used to instantiate a logger.

required

The factory has the following signature: factory(name, *args, **kwargs)

Source code in firebird/base/logging.py
def set_logger_factory(self, factory) -> None:
    """Set a callable which is used to create a Logger.

    Parameters:
        factory: The factory callable to be used to instantiate a logger.

    The factory has the following signature: `factory(name, *args, **kwargs)`
    """
    self._logger_factory = factory

set_topic_mapping(topic: str, new_topic: str | None) -> None

Sets or removes the mapping of an topic name to another name.

Parameters:

Name Type Description Default
topic str

Topic name.

required
new_topic str | None

Either None or new topic name.

required
  • When new_topic is a string, it maps topic to new_topic. Empty string is like None.
  • When new_topic is None, it removes any mapping.
Important

Does not validate the new_topic value type, instead it's converted to string.

Source code in firebird/base/logging.py
def set_topic_mapping(self, topic: str, new_topic: str | None) -> None:
    """Sets or removes the mapping of an topic name to another name.

    Arguments:
        topic: Topic name.
        new_topic: Either `None` or new topic name.

    - When `new_topic` is a string, it maps `topic` to `new_topic`. Empty string is
      like `None`.
    - When `new_topic` is `None`, it removes any mapping.

    Important:
        Does not validate the `new_topic` value type, instead it's converted to string.
    """
    if new_topic:
        self._topic_map[topic] = str(new_topic)
    else:
        self._topic_map.pop(topic, None)

Messages

firebird.base.logging.FStrMessage

Lazy logging message wrapper using f-string semantics via eval.

Defers the evaluation of the f-string until the message is actually formatted by a handler, improving performance if the message might be filtered out by log level settings.

Danger

Uses eval() internally. Ensure the format string and arguments do not contain untrusted user input.

Example
logger.debug(FStrMessage("Processing item {item_id} for user {user!r}",
                        item_id=123, user="Alice"))
# Formatting only happens if DEBUG level is enabled for the logger/handler.
Source code in firebird/base/logging.py
class FStrMessage:
    """Lazy logging message wrapper using f-string semantics via `eval`.

    Defers the evaluation of the f-string until the message is actually
    formatted by a handler, improving performance if the message might be
    filtered out by log level settings.

    Danger:
        Uses `eval()` internally. Ensure the format string and arguments
        do not contain untrusted user input.

    Example:
        ```python
        logger.debug(FStrMessage("Processing item {item_id} for user {user!r}",
                                item_id=123, user="Alice"))
        # Formatting only happens if DEBUG level is enabled for the logger/handler.
        ```
    """
    def __init__(self, fmt: str, /, *args, **kwargs):
        self.fmt: str = fmt
        self.args: tuple[Any, ...] = args
        self.kwargs: dict[str, Any] = kwargs
        if (args and len(args) == 1 and isinstance(args[0], Mapping) and args[0]):
            self.kwargs = args[0]
        else:
            self.kwargs = kwargs
            if args:
                self.kwargs['args'] = args
    def __str__(self) -> str:
        return eval(f'f"""{self.fmt}"""', globals(), self.kwargs) # noqa: S307

firebird.base.logging.BraceMessage

Lazy logging message wrapper using brace (str.format) style formatting.

Defers the call to str.format() until the message is actually formatted by a handler, improving performance for potentially filtered messages.

Example
logger.warning(BraceMessage("Connection failed: host={0}, port={1}",
                            'server.com', 8080))
logger.warning(BraceMessage(("Message with coordinates: ({point.x:.2f}, {point.y:.2f})",
                             point=point))
Source code in firebird/base/logging.py
class BraceMessage:
    """Lazy logging message wrapper using brace (`str.format`) style formatting.

    Defers the call to `str.format()` until the message is actually formatted
    by a handler, improving performance for potentially filtered messages.

    Example:
        ```python
        logger.warning(BraceMessage("Connection failed: host={0}, port={1}",
                                    'server.com', 8080))
        logger.warning(BraceMessage(("Message with coordinates: ({point.x:.2f}, {point.y:.2f})",
                                     point=point))
        ```
    """
    def __init__(self, fmt: str, /, *args, **kwargs):
        self.fmt: str = fmt
        self.args: tuple[Any, ...] = args
        self.kwargs: dict[str, Any] = kwargs
    def __str__(self) -> str:
        return self.fmt.format(*self.args, **self.kwargs)

firebird.base.logging.DollarMessage

Lazy logging message wrapper using dollar (string.Template) style formatting.

Defers the substitution using string.Template until the message is actually formatted by a handler, improving performance for potentially filtered messages.

Example
from string import Template # Not strictly needed for caller
logger.info(DollarMessage("Task $name completed with status $status",
                          name='Cleanup', status='Success'))
Source code in firebird/base/logging.py
class DollarMessage:
    """Lazy logging message wrapper using dollar (`string.Template`) style formatting.

    Defers the substitution using `string.Template` until the message is actually
    formatted by a handler, improving performance for potentially filtered messages.

    Example:
        ```python
        from string import Template # Not strictly needed for caller
        logger.info(DollarMessage("Task $name completed with status $status",
                                  name='Cleanup', status='Success'))
        ```
    """
    def __init__(self, fmt: str, /, **kwargs):
        self.fmt: str = fmt
        self.kwargs: dict[str, Any] = kwargs
    def __str__(self) -> str:
        from string import Template
        return Template(self.fmt).substitute(**self.kwargs)

Globals

firebird.base.logging.logging_manager: LoggingManager module-attribute

Context logging manager.