Adapters module
Implementations of logging.LoggerAdapter.
ContextualAdapter
Bases: LoggerAdapter
A logging.LoggerAdapter that can manage its own independent context.
Use this if you want to add context only to a given logger.
Example usage:
# Set up everything
>>> import logging
>>> from logging_with_context.adapters import ContextualAdapter
>>> from logging_with_context.formatters import ExtraTextFormatter
>>> logging.basicConfig(level=logging.INFO)
>>> root = logging.getLogger()
# To be able to see the context in the interpreter.
>>> root.handlers[0].setFormatter(
... ExtraTextFormatter(parent=root.handlers[0].formatter)
... )
# Using the adapter
>>> adapter = ContextualAdapter(root)
>>> with adapter.context({"key": "value"}) as logger:
... logger.info("This contains context")
... root.info("This does not")
INFO:root:This contains context |key="value"|
INFO:root:This does not
Source code in src/logging_with_context/adapters.py
__init__(logger, context=None)
Constructor:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logger
|
Logger
|
The logger to decorate with this adapter. |
required |
context
|
Optional[MutableMapping[str, object]]
|
The initial context; by default an empty context will be used. |
None
|
Source code in src/logging_with_context/adapters.py
context(context)
Creates a copy of itself with new context added, managed by a context manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
dict[str, Any]
|
The context to add. |
required |
Returns:
| Type | Description |
|---|---|
None
|
A context manager that yields an |
Source code in src/logging_with_context/adapters.py
process(msg, kwargs)
Merges the message extra keys with the context, giving preference to the
context.