Skip to content

xtr_logging_contracts

The logging contract: what code that logs depends on, and nothing more.

A library that logs should not decide where records go. It takes a :class:LoggerInterface, defaults to a :class:NullLogger, and leaves handlers, formatters and configuration to the application that wires it — so depending on this package costs a library nothing but the contract.

What is here is only what appears in that contract: the interface itself, the :class:Context and :class:Level its methods accept, and the two ways of satisfying it — :class:AbstractLogger to implement it in one method, and :class:NullLogger to implement it in none. Everything that acts on what was logged — records, handlers, processors, formatters, configuration — is xtr-logging, which implements this contract and re-exports it, so the two are never two different objects.

from xtr_logging_contracts import LoggerInterface, NullLogger


class Checkout:
    def __init__(self, logger: LoggerInterface | None = None) -> None:
        self._logger = logger or NullLogger()

EXCEPTION_KEY module-attribute

EXCEPTION_KEY: Final = 'exception'

The context key reserved for an exception to report.

Part of the contract rather than of any implementation: a library puts the exception it is reporting here, and whatever writes the record knows to look for it.

Context

Context = Mapping[str, object]

Structured data attached to what is logged.

Values are object because a caller may log anything; an implementation normalises what it cannot serialise rather than refusing it.

LevelLike

LevelLike = Level | int | str

Anything :meth:Level.parse accepts.

AbstractLogger

Bases: LoggerInterface, ABC

Implements every severity method in terms of :meth:log.

Subclass it and write log alone.

log abstractmethod

log(level: LevelLike, message: str, /, context: Context | None = None) -> None

Log message at level.

emergency

emergency(message: str, /, context: Context | None = None) -> None

Log at :attr:Level.EMERGENCY.

alert

alert(message: str, /, context: Context | None = None) -> None

Log at :attr:Level.ALERT.

critical

critical(message: str, /, context: Context | None = None) -> None

Log at :attr:Level.CRITICAL.

error

error(message: str, /, context: Context | None = None) -> None

Log at :attr:Level.ERROR.

warning

warning(message: str, /, context: Context | None = None) -> None

Log at :attr:Level.WARNING.

notice

notice(message: str, /, context: Context | None = None) -> None

Log at :attr:Level.NOTICE.

info

info(message: str, /, context: Context | None = None) -> None

Log at :attr:Level.INFO.

debug

debug(message: str, /, context: Context | None = None) -> None

Log at :attr:Level.DEBUG.

InvalidLevelError

InvalidLevelError(value: object)

Bases: LoggingError, ValueError

A value names no log level.

Also a :class:ValueError, which is what lets a configuration parser report the field that held it.

Record the value that could not be read as a level.

LoggingError

Bases: Exception

Base class for every error raised by this library.

Catch this to handle anything logging can go wrong with; catch a subclass to handle one cause. Every subclass carries the data a caller needs as typed attributes and composes its own message from them.

Level

Bases: IntEnum

A log level, ordered from least to most severe.

rfc5424 property

rfc5424: int

The RFC 5424 severity: 0 for EMERGENCY through 7 for DEBUG.

parse classmethod

parse(value: LevelLike) -> Level

Read any accepted spelling of a level.

Accepts a :class:Level, its value (400), an RFC 5424 severity (3), or a name in any case ("error", "ERROR").

Raises:

from_name classmethod

from_name(name: str) -> Level

Return the level called name, in any case.

Raises:

includes

includes(other: Level) -> bool

Whether a threshold of this level lets other through.

is_lower_than

is_lower_than(other: Level) -> bool

Whether this level is strictly less severe than other.

LoggerAware

Bases: LoggerAwareInterface

Holds a logger, defaulting to a :class:NullLogger.

Code in the class logs through :attr:logger without checking whether one was ever set.

logger property

logger: LoggerInterface

The logger set last, or one that discards everything.

set_logger

set_logger(logger: LoggerInterface) -> None

Log through logger from now on.

LoggerAwareInterface

Bases: Protocol

Accepts a logger through a setter.

Prefer a constructor argument. This exists for objects a framework builds for you, where the constructor is not yours to extend.

set_logger

set_logger(logger: LoggerInterface) -> None

Log through logger from now on.

LoggerInterface

Bases: Protocol

Writes messages at one of eight severities, with structured context.

The only type code that logs should depend on. Whatever implements it — a channel of xtr-logging's Logger, a :class:~xtr_logging_contracts.null_logger.NullLogger, an adapter over a standard library logger — can be swapped without touching a call site.

The rules:

  • message may hold {key} placeholders naming entries of context. The logger does not substitute them; something later in the pipeline does — xtr-logging's PlaceholderProcessor — so a handler may still see the template and the values apart.
  • An exception to report goes under context["exception"].
  • Context is data, never code: an implementation must not fail because of what it holds.

message is positional-only, so an implementation may name it freely; context may also be passed by keyword.

emergency

emergency(message: str, /, context: Context | None = None) -> None

The system is unusable.

alert

alert(message: str, /, context: Context | None = None) -> None

Action must be taken immediately — the whole site is down, say.

critical

critical(message: str, /, context: Context | None = None) -> None

A critical condition, such as an unavailable component.

error

error(message: str, /, context: Context | None = None) -> None

A runtime error that needs no immediate action but must be seen.

warning

warning(message: str, /, context: Context | None = None) -> None

Something exceptional that is not an error, like a deprecated call.

notice

notice(message: str, /, context: Context | None = None) -> None

A normal but significant event.

info

info(message: str, /, context: Context | None = None) -> None

An interesting event, such as a user logging in.

debug

debug(message: str, /, context: Context | None = None) -> None

Detailed information for debugging.

log

log(level: LevelLike, message: str, /, context: Context | None = None) -> None

Log at level, given in any form :meth:Level.parse accepts.

Raises:

NullLogger

Bases: AbstractLogger

Discards everything it is given.

The default for a library that accepts a logger: logging stays optional for its callers, and the library's code never has to ask whether it has one.

log

log(level: LevelLike, message: str, /, context: Context | None = None) -> None

Do nothing — not even check level, which costs a call site nothing.