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:
- Adds context information into
logging.LogRecord, that could be used in logging entry formats. - 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:
or for direct use:
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_contextattribute onagentinstance, or by assigning its value directly toextra['context']on adapter returned byget_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:
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
¶
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
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 |
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 |
required |
agent_name
|
str
|
The resolved string name for the agent. |
required |
Source code in firebird/base/logging.py
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.extracontainsdomain,topic, andagent(from init). - Adds
contexttoself.extra, taking it fromself.agent.log_contextif available, otherwiseNone. - Merges the adapter's
extradictionary with anyextradictionary passed inkwargs, giving precedence to keys inkwargs['extra']. - Stores the final merged
extradictionary intokwargs['extra'].
Returns:
| Type | Description |
|---|---|
tuple[Any, dict[str, Any]]
|
The possibly modified |
Source code in firebird/base/logging.py
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
Source code in firebird/base/logging.py
Logging manager¶
firebird.base.logging.LoggingManager
¶
Logging manager.
Source code in firebird/base/logging.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 | |
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.
get_agent_domain(agent: str) -> str | None
¶
get_agent_mapping(agent: str) -> str | None
¶
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:
- If
agentis a string, it's used directly. - If
agentis an object: - Uses
agent._agent_name_if defined (converting to string if needed). - Otherwise, constructs name as
module.ClassQualname. - Applies any agent name mapping defined via
set_agent_mappingto the name determined in steps 1 or 2. - Ensures the final result is a string.
Example
Source code in firebird/base/logging.py
get_domain_mapping(domain: str) -> set[str] | None
¶
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
|
required |
topic
|
str | None
|
Optional topic string for the logging stream (e.g., 'network', 'db'). |
None
|
Returns:
| Type | Description |
|---|---|
ContextLoggerAdapter
|
A |
Process Flow:
- Determine
agent_nameusingget_agent_name(agent). - Determine
domainby looking upagent_namein the domain mapping, falling back toself.default_domain. - Apply topic mapping to the input
topic(if any). - Construct the final underlying
logging.Loggername usingself.logger_fmt, substituting the determineddomainand mappedtopic. - Get/create the
logging.Loggerinstance usingself._logger_factorywith the constructed name. - Create and return a
ContextLoggerAdapterwrapping the logger and carrying thedomain, mappedtopic, originalagent, andagent_name.
Source code in firebird/base/logging.py
get_logger_factory() -> Callable
¶
get_topic_mapping(topic: str) -> str | None
¶
reset() -> None
¶
Resets manager to "factory defaults": no mappings, no logger_fmt and undefined
default_domain.
Source code in firebird/base/logging.py
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 |
required |
Important
Does not validate the new_agent value type, instead it's converted to string.
Source code in firebird/base/logging.py
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 |
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
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
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 |
required |
- When
new_topicis a string, it mapstopictonew_topic. Empty string is likeNone. - When
new_topicisNone, 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
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
Source code in firebird/base/logging.py
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
Source code in firebird/base/logging.py
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
Source code in firebird/base/logging.py
Globals¶
firebird.base.logging.logging_manager: LoggingManager
module-attribute
¶
Context logging manager.