Merge per-call context with LoggerAdapter in Python 3.13
Python 3.13 adds merge_extra=True to LoggerAdapter. It lets a call add or override context while retaining the adapter’s defaults; the default adapter behavior ignores per-call extra.
Run the example
Tested on Linux with Python 3.13.5. No third-party packages or network access are needed. In one Bash session, create a temporary working directory:
demo_start="$PWD"
demo_dir="$(mktemp -d)" || exit 1
cd -- "$demo_dir" || exit 1Save as demo_log_context.py in that directory. Use this filename to avoid shadowing a standard-library module.
import logging
import sys
logger = logging.getLogger("context_demo")
logger.setLevel(logging.INFO)
logger.propagate = False
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter(
"%(service)s %(request_id)s %(message)s"))
logger.addHandler(handler)
try:
defaults = {"service": "report", "request_id": "-"}
ordinary = logging.LoggerAdapter(logger, defaults)
merged = logging.LoggerAdapter(logger, defaults, merge_extra=True)
ordinary.info("default adapter", extra={"request_id": "r17"})
merged.info("merged adapter", extra={"request_id": "r17"})
merged.info("defaults retained")
finally:
logger.removeHandler(handler)
handler.close()Run it:
python3.13 demo_log_context.pyCaptured output:
report - default adapter
report r17 merged adapter
report - defaults retainedInterpret the result
The per-call request identifier replaces the adapter default only for the merged call. The next call uses the defaults again. Providing a default for every custom formatter field avoids missing-field formatting failures in these records. Do not use reserved LogRecord attribute names as extra keys, and do not place secrets in logging context. This example installs a handler only on its named logger, avoids propagation, and removes the handler afterward. Python 3.12 does not accept the merge_extra constructor argument.
See the version-specific Python reference for the API contract.
Clean up
In the same Bash session, remove the source file and then the empty working directory:
rm -- demo_log_context.py
cd -- "$demo_start" || exit 1
rmdir -- "$demo_dir"
unset demo_start demo_dirIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.