mode.utils.logging

Logging utilities.

mode.utils.logging.FormatterHandler

alias of typing.Callable

mode.utils.logging.get_logger(name: str) → logging.Logger[source]

Get logger by name.

class mode.utils.logging.LogSeverityMixin[source]

Mixin class that delegates standard logging methods to logger.

The class that mixes in this class must define the log method.

Example

>>> class Foo(LogSeverityMixin):
...
...    logger = get_logger('foo')
...
...    def log(self,
...            severity: int,
...            msg: str,
...            *args: Any, **kwargs: Any) -> None:
...        return self.logger.log(severity, msg, *args, **kwargs)
dev(msg: str, *args: Any, **kwargs: Any) → None[source]
debug(msg: str, *args: Any, **kwargs: Any) → None[source]
info(msg: str, *args: Any, **kwargs: Any) → None[source]
warn(msg: str, *args: Any, **kwargs: Any) → None[source]
warning(msg: str, *args: Any, **kwargs: Any) → None[source]
error(msg: str, *args: Any, **kwargs: Any) → None[source]
crit(msg: str, *args: Any, **kwargs: Any) → None[source]
critical(msg: str, *args: Any, **kwargs: Any) → None[source]
exception(msg: str, *args: Any, **kwargs: Any) → None[source]
class mode.utils.logging.CompositeLogger(logger: logging.Logger, formatter: Callable[..., str] = None)[source]

Composite logger for classes.

The class can be used as both mixin and composite, and may also define a .formatter attribute which will reformat any log messages sent.

Service uses this to add logging methods:

class Service(ServiceT):

    log: CompositeLogger

    def __init__(self):
        self.log = CompositeLogger(
            logger=self.logger,
            formatter=self._format_log,
        )

    def _format_log(self, severity: int, msg: str,
                    *args: Any, **kwargs: Any) -> str:
        return (f'[^{"-" * (self.beacon.depth - 1)}'
                f'{self.shortlabel}]: {msg}')

This means those defining a service may also use it to log:

>>> service.log.info('Something happened')

and when logging additional information about the service is automatically included.

log(severity: int, msg: str, *args: Any, **kwargs: Any) → None[source]
format(severity: int, msg: str, *args: Any, **kwargs: Any) → str[source]
mode.utils.logging.formatter(fun: Callable[Any, Any]) → Callable[Any, Any][source]

Register formatter for logging positional args.

class mode.utils.logging.ExtensionFormatter(stream: IO = None, **kwargs: Any)[source]

Formatter that can register callbacks to format args.

Extends colorlog.

format(record: logging.LogRecord) → str[source]

Format a message from a record object.

mode.utils.logging.level_name(loglevel: int) → str[source]

Convert log level to number.

mode.utils.logging.level_number(loglevel: int) → int[source]

Convert log level number to name.

mode.utils.logging.setup_logging(*, loglevel: Union[str, int] = None, logfile: Union[str, IO] = None, loghandlers: List[logging.StreamHandler] = None, logging_config: Dict = None) → int[source]

Configure logging subsystem.

class mode.utils.logging.Logwrapped(obj: Any, logger: Any = None, severity: Union[int, str] = None, ident: str = '')[source]

Wrap all object methods, to log on call.

mode.utils.logging.cry(file: IO, *, sep1: str = '=', sep2: str = '-', sep3: str = '~', seplen: int = 49) → None[source]

Return stack-trace of all active threads.

See also

Taken from https://gist.github.com/737056.

class mode.utils.logging.flight_recorder(logger: Any, *, timeout: Union[datetime.timedelta, float, str], loop: asyncio.events.AbstractEventLoop = None)[source]

Flight Recorder context for use with with statement.

This is a logging utility to log stuff only when something times out.

For example if you have a background thread that is sometimes hanging:

class RedisCache(mode.Service):

    @mode.timer(1.0)
    def _background_refresh(self) -> None:
        self._users = await self.redis_client.get(USER_KEY)
        self._posts = await self.redis_client.get(POSTS_KEY)

You want to figure out on what line this is hanging, but logging all the time will provide way too much output, and will even change how fast the program runs and that can mask race conditions, so that they never happen.

Use the flight recorder to save the logs and only log when it times out:

logger = mode.get_logger(__name__)

class RedisCache(mode.Service):

    @mode.timer(1.0)
    def _background_refresh(self) -> None:
        with mode.flight_recorder(logger, timeout=10.0) as on_timeout:
            on_timeout.info(f'+redis_client.get({USER_KEY!r})')
            await self.redis_client.get(USER_KEY)
            on_timeout.info(f'-redis_client.get({USER_KEY!r})')

            on_timeout.info(f'+redis_client.get({POSTS_KEY!r})')
            await self.redis_client.get(POSTS_KEY)
            on_timeout.info(f'-redis_client.get({POSTS_KEY!r})')

If the body of this with statement completes before the timeout, the logs are forgotten about and never emitted – if it takes more than ten seconds to complete, we will see these messages in the log:

[2018-04-19 09:43:55,877: WARNING]: Warning: Task timed out!
[2018-04-19 09:43:55,878: WARNING]:
    Please make sure it is hanging before restarting.
[2018-04-19 09:43:55,878: INFO]: [Flight Recorder-1]
    (started at Thu Apr 19 09:43:45 2018) Replaying logs...
[2018-04-19 09:43:55,878: INFO]: [Flight Recorder-1]
    (Thu Apr 19 09:43:45 2018) +redis_client.get('user')
[2018-04-19 09:43:55,878: INFO]: [Flight Recorder-1]
    (Thu Apr 19 09:43:49 2018) -redis_client.get('user')
[2018-04-19 09:43:55,878: INFO]: [Flight Recorder-1]
    (Thu Apr 19 09:43:46 2018) +redis_client.get('posts')
[2018-04-19 09:43:55,878: INFO]: [Flight Recorder-1] -End of log-

Now we know this redis_client.get call can take too long to complete, and should consider adding a timeout to it.

wrap_debug(obj: Any) → mode.utils.logging.Logwrapped[source]
wrap_info(obj: Any) → mode.utils.logging.Logwrapped[source]
wrap_warn(obj: Any) → mode.utils.logging.Logwrapped[source]
wrap_error(obj: Any) → mode.utils.logging.Logwrapped[source]
wrap(severity: int, obj: Any) → mode.utils.logging.Logwrapped[source]
activate() → None[source]
cancel() → None[source]
log(severity: int, message: str, *args: Any, **kwargs: Any) → None[source]
class mode.utils.logging.FileLogProxy(logger: logging.Logger, *, severity: Union[int, str] = None)[source]

File-like object that forwards data to logger.

mode = 'w'
name = None
closed = False
severity = 30
write(data: Any) → None[source]
writelines(lines: Sequence[str]) → None[source]
flush() → None[source]
close() → None[source]
isatty() → bool[source]
mode.utils.logging.redirect_stdouts(logger: logging.Logger = <Logger mode.redirect (WARNING)>, *, severity: Union[int, str] = None, stdout: bool = True, stderr: bool = True) → ContextManager[mode.utils.logging.FileLogProxy][source]

Redirect sys.stdout and sys.stdout to logger.