Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Logging warnings with team context using `LoggerAdapter`

Wrap an existing logger in `logging.LoggerAdapter` with a `team` field so that `info`, `warning`, and `error` calls all carry the same team context.

Version: Python 3.12

Syntax

adapter = logging.LoggerAdapter(logger, {"team": "Platform"})
adapter.info(msg, *args, **kwargs)
adapter.warning(msg, *args, **kwargs)
adapter.error(msg, *args, **kwargs)

In Python 3.12, logging.LoggerAdapter(logger, {"team": "Platform"}) wraps an existing logger and forwards calls to it with team context. Use adapter.warning(...) for a WARNING when something unexpected has happened or a problem may be developing. Use adapter.info(...) for normal progress (INFO) and adapter.error(...) for a failed operation (ERROR). These are not the module-level logging.info, logging.warning, and logging.error functions: those use the root logger and do not automatically receive the adapter’s context.

In Python 3.12, the default process() leaves the message unchanged and passes the constructor’s mapping as extra. If you supply extra in an individual adapter call, it is replaced, not merged. team becomes a LogRecord attribute, so a Formatter can display it with %(team)s. Keys in extra must not collide with reserved record attributes.

Every record handled by that formatter must have team; otherwise formatting fails. The logger and handler configuration still determines whether a message is emitted. In the example, the INFO threshold admits all three levels.

Examples

import logging
import sys

logger = logging.getLogger("ck tis.deployment".replace(" ", ""))
logger.setLevel(logging.INFO)
logger.propagate = False

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(levelname)s [%(team)s] %(message)s"))
logger.addHandler(handler)

adapter = logging.LoggerAdapter(logger, {"team": "Platform"})
adapter.info("Deployment started")
adapter.warning("Retrying health check")
adapter.error("Deployment failed")

Result

INFO [Platform] Deployment started
WARNING [Platform] Retrying health check
ERROR [Platform] Deployment failed

Run this as a standalone Python 3.12 script. The handler writes to standard output, and disabling propagation prevents records from reaching ancestor loggers. Expect three lines, each containing `[Platform]`.

Related lessons

  • Python · Lesson 27 · Advanced · Version: 5

Sources