Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

LoggerAdapter.error(): logging errors with team context

In Python 3.12, use `LoggerAdapter.error()` to log at `ERROR` level with a `team` field you don’t have to pass on each call.

Version: Python 3.12

Syntax

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

Create the adapter with logging.LoggerAdapter(logger, extra={"team": "platform"}). A call to adapter.error() logs at ERROR level through the supplied Logger, whereas the module-level logging.error() uses the root logger. The adapter has no threshold of its own: the logger and handler settings determine whether a record is emitted.

Use adapter.error() to report a failure. The call does not itself raise an exception or include a traceback by default. Inside except, use adapter.exception(...) or adapter.error(..., exc_info=True) to include the exception being handled.

In Python 3.12, the default process() replaces any per-call extra with the constructor's context rather than merging them. The team field becomes a LogRecord attribute; the formatter displays it with %(team)s. Avoid names of built-in attributes such as levelname. If a formatter expects team and a record lacks that field, formatting fails unless a default is configured.

Examples

import logging
import sys

logger = logging.getLogger("deploy")
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, extra={"team": "platform"})
adapter.info("Deployment started for %s", "api")
adapter.warning("Health check is slow")
adapter.error("Deployment failed")

Result

INFO [platform] Deployment started for api
WARNING [platform] Health check is slow
ERROR [platform] Deployment failed

Run as a standalone script. The `INFO` threshold allows all three records, and the `StreamHandler` writes them to standard output. `propagate = False` prevents forwarding them to ancestor handlers.

Related lessons

  • Python · Lesson 27 · Advanced · Version: 5

Sources