Skip to content

Logging

Utilities for setting up and managing logging.


LoggingMixin

Mixin that provides a cached logger instance based on the class name.

log property

log

Alias for logger.

logger cached property

logger

A logger named after the module and class.

enable_stdout_logging

enable_stdout_logging()

Enable stdout logging for this instance's logger.

Source code in src/aibs_informatics_core/utils/logging.py
187
188
189
def enable_stdout_logging(self):
    """Enable stdout logging for this instance's logger."""
    enable_stdout_logging(self.logger)

log_stacktrace

log_stacktrace(message, error)

Log an error message and its stack trace.

Parameters:

Name Type Description Default
message str

Error message to log.

required
error BaseException

The exception to log.

required
Source code in src/aibs_informatics_core/utils/logging.py
177
178
179
180
181
182
183
184
185
def log_stacktrace(self, message: str, error: BaseException):
    """Log an error message and its stack trace.

    Args:
        message: Error message to log.
        error: The exception to log.
    """
    self.logger.error(message)
    self.logger.exception(error)

check_formatter_equality

check_formatter_equality(this, other)

Check if two formatters are equivalent.

Parameters:

Name Type Description Default
this Formatter | None

First formatter (or None).

required
other Formatter | None

Second formatter (or None).

required

Returns:

Type Description
bool

True if both formatters have the same format and datefmt.

Source code in src/aibs_informatics_core/utils/logging.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def check_formatter_equality(
    this: logging.Formatter | None, other: logging.Formatter | None
) -> bool:
    """Check if two formatters are equivalent.

    Args:
        this: First formatter (or None).
        other: Second formatter (or None).

    Returns:
        True if both formatters have the same format and datefmt.
    """
    if this is None and other is None:
        return True
    if this is None or other is None:
        return False
    else:
        return this._fmt == other._fmt and this.datefmt == other.datefmt

check_handler_equality

check_handler_equality(this, other)

Check if two handlers are equivalent.

Compares type, level, name, and formatter.

Parameters:

Name Type Description Default
this Handler

First handler.

required
other Handler

Second handler.

required

Returns:

Type Description
bool

True if both handlers are equivalent.

Source code in src/aibs_informatics_core/utils/logging.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def check_handler_equality(this: logging.Handler, other: logging.Handler) -> bool:
    """Check if two handlers are equivalent.

    Compares type, level, name, and formatter.

    Args:
        this: First handler.
        other: Second handler.

    Returns:
        True if both handlers are equivalent.
    """
    if type(this) is not type(other):
        return False
    if this.level != other.level:
        return False
    if this.get_name() != other.get_name():
        return False
    if not check_formatter_equality(this.formatter, other.formatter):
        return False
    return True

enable_stdout_logging

enable_stdout_logging(
    logger, format=DEFAULT_LOGGING_FORMAT, level="INFO"
)

Enable stdout logging for a logger if not already configured.

Parameters:

Name Type Description Default
logger StrOrLogger

Logger instance or name.

required
format StrOrFormatter

Format string or existing Formatter instance.

DEFAULT_LOGGING_FORMAT
level LogLevel

Logging level for the handler.

'INFO'

Returns:

Type Description
Logger

The configured logging.Logger instance.

Source code in src/aibs_informatics_core/utils/logging.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def enable_stdout_logging(
    logger: StrOrLogger, format: StrOrFormatter = DEFAULT_LOGGING_FORMAT, level: LogLevel = "INFO"
) -> logging.Logger:
    """Enable stdout logging for a logger if not already configured.

    Args:
        logger: Logger instance or name.
        format: Format string or existing Formatter instance.
        level: Logging level for the handler.

    Returns:
        The configured ``logging.Logger`` instance.
    """
    if not isinstance(logger, logging.Logger):
        logger = logging.getLogger(logger)

    handler = get_stdout_handler(format=format, level=level)

    if any([check_handler_equality(handler, existing) for existing in get_all_handlers(logger)]):
        return logger

    logger.addHandler(handler)
    return logger

get_all_handlers

get_all_handlers(logger)

Collect all handlers from a logger and its parent chain.

Parameters:

Name Type Description Default
logger Logger

The logger to inspect.

required

Returns:

Type Description
list[Handler]

A list of all handlers attached to the logger and its ancestors.

Source code in src/aibs_informatics_core/utils/logging.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def get_all_handlers(logger: logging.Logger) -> list[logging.Handler]:
    """Collect all handlers from a logger and its parent chain.

    Args:
        logger: The logger to inspect.

    Returns:
        A list of all handlers attached to the logger and its ancestors.
    """
    handlers: list[logging.Handler] = []
    if logger.handlers:
        handlers.extend(list(logger.handlers))
    while logger.parent:
        logger = logger.parent
        if logger.handlers:
            handlers.extend(list(logger.handlers))
    return handlers

get_formatter cached

get_formatter(format=DEFAULT_LOGGING_FORMAT)

Get or create a cached log formatter.

Parameters:

Name Type Description Default
format StrOrFormatter

Format string or existing Formatter instance.

DEFAULT_LOGGING_FORMAT

Returns:

Type Description
Formatter

A logging.Formatter instance.

Source code in src/aibs_informatics_core/utils/logging.py
40
41
42
43
44
45
46
47
48
49
50
51
@cache
def get_formatter(format: StrOrFormatter = DEFAULT_LOGGING_FORMAT) -> logging.Formatter:
    """Get or create a cached log formatter.

    Args:
        format: Format string or existing Formatter instance.

    Returns:
        A ``logging.Formatter`` instance.
    """
    formatter = logging.Formatter(format) if isinstance(format, str) else format
    return formatter

get_logger

get_logger(name=None)

Get a logger by name.

Parameters:

Name Type Description Default
name str | None

Logger name. If None, returns the root logger.

None

Returns:

Type Description

A logging.Logger instance.

Source code in src/aibs_informatics_core/utils/logging.py
28
29
30
31
32
33
34
35
36
37
def get_logger(name: str | None = None):
    """Get a logger by name.

    Args:
        name: Logger name. If None, returns the root logger.

    Returns:
        A ``logging.Logger`` instance.
    """
    return logging.getLogger(name=name)

get_stdout_handler cached

get_stdout_handler(
    format=DEFAULT_LOGGING_FORMAT, level="INFO"
)

Get or create a cached stdout stream handler.

Parameters:

Name Type Description Default
format StrOrFormatter

Format string or existing Formatter instance.

DEFAULT_LOGGING_FORMAT
level LogLevel

Logging level for the handler.

'INFO'

Returns:

Type Description
StreamHandler

A logging.StreamHandler writing to stdout.

Source code in src/aibs_informatics_core/utils/logging.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
@cache
def get_stdout_handler(
    format: StrOrFormatter = DEFAULT_LOGGING_FORMAT, level: LogLevel = "INFO"
) -> logging.StreamHandler:
    """Get or create a cached stdout stream handler.

    Args:
        format: Format string or existing Formatter instance.
        level: Logging level for the handler.

    Returns:
        A ``logging.StreamHandler`` writing to stdout.
    """
    formatter = get_formatter(format)

    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(formatter)
    handler.setLevel(level)

    return handler