lewis.core.logging

This module contains everything logging-related in Lewis. There is one relevant module level variable that defines the default log format, default_log_format.

All places that use logging in Lewis prefix their logger names with lewis so that you can easily control the logs caused by Lewis if you use it as a library. Lewis uses the default settings of the logging module, so if you use Lewis as a library and do not have any logging enabled, messages that are more severe than WARNING are printed to stdout. For details on how to disable that behavior, change levels for certain loggers and so on, please refer to the documentation of the standard logging library.

Members

HasLog

has_log

This is a decorator to add logging functionality to a class or function.

class lewis.core.logging.HasLog(*args, **kwargs)[source]

Bases: Protocol

lewis.core.logging.has_log(target: Type[T]) Type[T][source]
lewis.core.logging.has_log(target: Callable[[P], T]) Callable[[P], T]

This is a decorator to add logging functionality to a class or function.

Applying this decorator to a class or function will add two new members:

  • log is an instance of logging.Logger. The name of the logger is set to lewis.Foo for a class named Foo.

  • _set_logging_context is a method that modifies the name of the logger when the class is used in a certain context.

If context is a string, that string is directly inserted between lewis and Foo, so that the logger name would be lewis.bar.Foo if context was 'bar'. The more common case is probably context being an object of some class, in which case the class name is inserted. If context is an object of type Bar, the logger name of Foo would be lewis.Bar.Foo.

To provide a more concrete example in terms of Lewis, this is used for the state machine logger in a device. So the logs of the state machine belonging to a certain device appear in the log as originating from lewis.DeviceName.StateMachine, which makes it possible to distinguish between messages from different state machines.

Example for how to use logging in a class:

from lewis.core.logging import has_log


@has_log
class Foo(Base):
    def __init__(self):
        super(Foo, self).__init__()

    def bar(self, baz):
        self.log.debug("Called bar with parameter baz=%s", baz)
        return baz is not None

It works similarly for free functions, although the actual logging calls are a bit different:

from lewis.core.logging import has_log


@has_log
def foo(bar):
    foo.log.info("Called with argument bar=%s", bar)
    return bar

The name of the logger is lewis.foo, the context could also be modified by calling foo._set_logging_context.

Parameters:

target – Target to decorate with logging functionality.