logalpha.handler




The base Handler class should be considered an abstract class. If deriving directly from the base class you should implement both the format() and the write(). methods.

class Handler(level: Level, resource: Any)[source]

Core message handling interface. A Handler associates a level with a resource.

Attributes:
level (Level):

The level for this handler.

resource (Any):

Some resource to publish messages to.

write(message: logalpha.message.Message) → None[source]

Publish message to resource after calling format.

format(message: logalpha.message.Message) → Any[source]

Format message.



A minimum viable implementation is provided in StreamHandler. This handler wants a file-like resource to write to. It’s write() method literally calls print() with the resource as the file.

class StreamHandler(level: Level = Level(name='WARNING', value=2), resource: IO = <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>)[source]

Bases: logalpha.handler.Handler

Publish messages to a file-like resource.

Attributes:
level (Level):

The level for this handler (default: WARNING).

resource (IO):

File-like resource to write to (default: sys.stderr).

write(message: logalpha.message.Message) → None[source]

Publish message to resource after calling format.

format(message: logalpha.message.Message) → str[source]

Returns message.content.


The StreamHandler class implements everything needed for messages to be published to stderr or some other file-like object. To customize formatting, extend the class by overriding the format() method. Just for formatting this seems like a lot of boilerplate; however, by making it a function call it’s possible to inject any arbitrary code.

@dataclass
class MyHandler(StreamHandler):
    """A :class:`~StreamHandler` with custom formatting."""

    def format(self, message: Message) -> str:
        return f'{message.level.name} {message.content}'