momotor.shared.log

Writing a log line can block on disk or network I/O. In async code that stalls the event loop. This module wraps a standard logging.Logger so log calls hand the actual writing to a background thread, while the calling code keeps the familiar logger interface.

Create an async logger

getAsyncLogger() mirrors logging.getLogger(). Log methods on the result are coroutines, so await them:

from momotor.shared.log import getAsyncLogger

logger = getAsyncLogger(__name__)

await logger.info('job %s started', job_id)
await logger.exception('job failed')

By default a log call returns as soon as the line is queued. Critical messages and messages with exception information wait until the line is written, so the last lines before a crash are not lost. Pass wait_for_completion to change this per logger or per call.

When you need the wrapped logger in synchronous code, use the sync attribute. It first waits for queued lines, so sync and async lines stay in order.

Log exceptions from a block

log_exception() and async_log_exception() are context managers. They log an exception that escapes the block, then swallow it or re-raise it, as you choose:

from momotor.shared.log import log_exception

with log_exception(logger.sync, 'cleanup failed'):
    cleanup()

Pass reraise=True to log and still propagate the exception. Pass ignore with an exception class, or a sequence of classes, for exceptions that must propagate without being logged.

API reference

class momotor.shared.log.AsyncLogWrapper(logger, *, wait_for_completion=False)

Wraps a Python logger for async use. The original logger is available on the sync attribute for use in synchronous code.

Most properties and methods from the original logger are proxied.

Parameters:
  • logger (Logger) – The Python logger to wrap

  • wait_for_completion (bool | None) – If True all logging statements will only return when the line is written to the log. If False will queue the line to be logged and return immediately. If None (default) will wait if the level of the logger is DEBUG

async static flush()

Wait until the last submitted logging statement has completed

static flush_sync()

Wait until the last submitted logging statement has completed

async critical(msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘CRITICAL’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.critical(“Houston, we have a %s”, “major disaster”, exc_info=1)

async debug(msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘DEBUG’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.debug(“Houston, we have a %s”, “thorny problem”, exc_info=1)

async error(msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘ERROR’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.error(“Houston, we have a %s”, “major problem”, exc_info=1)

async exception(msg, *args, exc_info=True, **kwargs)

Convenience method for logging an ERROR with exception information.

async fatal(msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘CRITICAL’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.critical(“Houston, we have a %s”, “major disaster”, exc_info=1)

getEffectiveLevel()

Get the effective level for this logger.

Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found.

async handle(record)

Call the handlers for the specified record.

This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied.

async info(msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘INFO’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.info(“Houston, we have a %s”, “interesting problem”, exc_info=1)

isEnabledFor(level)

Is this logger enabled for level ‘level’?

async log(level, msg, *args, **kwargs)

Log ‘msg % args’ with the integer severity ‘level’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.log(level, “We have a %s”, “mysterious problem”, exc_info=1)

setLevel(level)

Set the logging level of this logger. level must be an int or a str.

async warning(msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘WARNING’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.warning(“Houston, we have a %s”, “bit of a problem”, exc_info=1)

property disabled

Get/set the disabled property of the logger

property level

Get the level of the logger

property name

Get the name of the logger

property propagate

Get/set the propagate property of the logger

property sync: Logger

Get the original logger instance, for use in synchronous code, e.g.

logger.sync.info(“This is logged from synchronous code”)

momotor.shared.log.async_log_exception(async_logger, msg, *args, reraise=False, ignore=None)

An async context manager that captures exceptions, logs them, and optionally re-raises them.

Parameters:
  • async_logger (AsyncLogWrapper) – The async logger to log the exception to

  • msg (str) – A message to add to the exception

  • args – Any optional arguments for the message

  • reraise (bool) – If True, the exception will be re-raised after logging

  • ignore (type[Exception] | Sequence[type[Exception]] | None) – An exception class, or sequence of exception classes, to ignore. These exceptions will not be logged but always re-raised

momotor.shared.log.getAsyncLogger(name, *, wait_for_completion=False)

Convenience function to create an asynchronous logger. Creates the logger by calling logging.getLogger() and wraps it with AsyncLogWrapper

Parameters:
  • name – name of the logger

  • wait_for_completion (bool | None) – If True all logging statements will only return when the line is written to the log. If False will queue the line to be logged and return immediately. If None (default) will wait if the level of the logger is DEBUG

Return type:

AsyncLogWrapper

momotor.shared.log.log_exception(logger, msg, *args, reraise=False, ignore=None)

A context manager that captures exceptions, logs them, and optionally re-raises them.

Parameters:
  • logger (Logger) – The logger to log the exception to

  • msg (str) – A message to add to the exception

  • args – Any optional arguments for the message

  • reraise (bool) – If True, the exception will be re-raised after logging

  • ignore (type[Exception] | Sequence[type[Exception]] | None) – An exception class, or sequence of exception classes, to ignore. These exceptions will not be logged but always re-raised