Go to the latest version of this document.

# ``twisted`.`logger`.`Logger``

class documentation

`class Logger: (source)`

Constructor: `Logger(namespace, source, observer)`

View In Hierarchy

A `Logger` emits log messages to an observer. You should instantiate it as a class or module attribute, as documented in `this module's documentation`.

Method | `__get__` | When used as a descriptor, i.e.:
Method | `__init__` | No summary
Method | `__repr__` | Undocumented
Method | `critical` | Emit a log event at log level `LogLevel.critical`.
Method | `debug` | Emit a log event at log level `LogLevel.debug`.
Method | `emit` | Emit a log event to all log observers at the given level.
Method | `error` | Emit a log event at log level `LogLevel.error`.
Method | `failure` | Log a failure and emit a traceback.
Method | `failureHandler` | For performance-sensitive frameworks that needs to handle potential failures from frequently-called application code, and do not need to include detailed structured information about the failure nor inspect the result of the operation, this method returns a context manager that will log exceptions and continue, that can be shared across multiple invocations...
Method | `failuresHandled` | Run some application code, logging a failure and emitting a traceback in the event that any of it fails, but continuing on. For example:
Method | `info` | Emit a log event at log level `LogLevel.info`.
Method | `warn` | Emit a log event at log level `LogLevel.warn`.
Instance Variable | `namespace` | the namespace for this logger
Instance Variable | `observer` | The observer that this logger will send events to.
Instance Variable | `source` | The object which is emitting events via this logger
Static Method | `_namespaceFromCallingContext` | Derive a namespace from the module containing the caller's caller.

def __get__(self, instance: `object`, owner: `type | None` = None) -> `Logger`: (source)

When used as a descriptor, i.e.:

        # File: athing.py
        class Something:
            log = Logger()
            def hello(self):
                self.log.info("Hello")

a `Logger`'s namespace will be set to the name of the class it is declared on. In the above example, the namespace would be `athing.Something`.

Additionally, its source will be set to the actual object referring to the `Logger`. In the above example, `Something.log.source` would be `Something`, and `Something().log.source` would be an instance of `Something`.

def __init__(self, namespace: `str | None` = None, source: `object | None` = None, observer: `ILogObserver | None` = None): (source)

Parameters
namespace:`str | None` | The namespace for this logger. Uses a dotted notation, as used by python modules. If not `None`, then the name of the module of the caller is used.
source:`object | None` | The object which is emitting events via this logger; this is automatically set on instances of a class if this `Logger` is an attribute of that class.
observer:`ILogObserver | None` | The observer that this logger will send events to. If `None`, use the `global log publisher`.

def __repr__(self) -> `str`: (source)

Undocumented

def critical(self, format: `str | None` = None, **kwargs: `object`): (source)

Emit a log event at log level `LogLevel.critical`.

Parameters
format:`str | None` | a message format using new-style (PEP 3101) formatting. The logging event (which is a `dict`) is used to render this format string.
**kwargs:`object` | additional key/value pairs to include in the event. Note that values which are later mutated may result in non-deterministic behavior from observers that schedule work for later execution.

def debug(self, format: `str | None` = None, **kwargs: `object`): (source)

Emit a log event at log level `LogLevel.debug`.

Parameters
format:`str | None` | a message format using new-style (PEP 3101) formatting. The logging event (which is a `dict`) is used to render this format string.
**kwargs:`object` | additional key/value pairs to include in the event. Note that values which are later mutated may result in non-deterministic behavior from observers that schedule work for later execution.

def emit(self, level: `LogLevel`, format: `str | None` = None, **kwargs: `object`): (source)

Emit a log event to all log observers at the given level.

Parameters
level:`LogLevel` | a `LogLevel`
format:`str | None` | a message format using new-style (PEP 3101) formatting. The logging event (which is a `dict`) is used to render this format string.
**kwargs:`object` | additional key/value pairs to include in the event. Note that values which are later mutated may result in non-deterministic behavior from observers that schedule work for later execution.

def error(self, format: `str | None` = None, **kwargs: `object`): (source)

Emit a log event at log level `LogLevel.error`.

Parameters
format:`str | None` | a message format using new-style (PEP 3101) formatting. The logging event (which is a `dict`) is used to render this format string.
**kwargs:`object` | additional key/value pairs to include in the event. Note that values which are later mutated may result in non-deterministic behavior from observers that schedule work for later execution.

def failure(self, format: `str`, failure: `Failure | None` = None, level: `LogLevel` = LogLevel.critical, **kwargs: `object`): (source)

Log a failure and emit a traceback.

For example:

        try:
            frob(knob)
        except Exception:
            log.failure("While frobbing {knob}", knob=knob)

or:

        d = deferredFrob(knob)
        d.addErrback(lambda f: log.failure("While frobbing {knob}",
                                           f, knob=knob))

This method is meant to capture unexpected exceptions in code; an exception that is caught and handled somehow should be logged, if appropriate, via `Logger.error` instead. If some unknown exception occurs and your code doesn't know how to handle it, as in the above example, then this method provides a means to describe the failure. This is done at `LogLevel.critical` by default, since no corrective guidance can be offered to an user/administrator, and the impact of the condition is unknown.

Parameters
format:`str` | a message format using new-style (PEP 3101) formatting. The logging event (which is a `dict`) is used to render this format string.
failure:`Failure | None` | a `Failure` to log. If `None`, a `Failure` is created from the exception in flight.
level:`LogLevel` | a `LogLevel` to use.
**kwargs:`object` | additional key/value pairs to include in the event. Note that values which are later mutated may result in non-deterministic behavior from observers that schedule work for later execution.

See Also
`Logger.failureHandler`
`Logger.failuresHandled`

def failureHandler(self, staticMessage: `str`, level: `LogLevel` = LogLevel.critical) -> `ContextManager[None]`: (source)

For performance-sensitive frameworks that needs to handle potential failures from frequently-called application code, and do not need to include detailed structured information about the failure nor inspect the result of the operation, this method returns a context manager that will log exceptions and continue, that can be shared across multiple invocations. It should be instantiated at module scope to avoid additional object creations.

For example:

        log = Logger(...)
        ignoringFrobErrors = log.failureHandler("while frobbing:")

        def hotLoop() -> None:
            with ignoringFrobErrors:
                frob()

This method is meant to capture unexpected exceptions from application code; an exception that is caught and handled somehow should be logged, if appropriate, via `Logger.error` instead. If some unknown exception occurs and your code doesn't know how to handle it, as in the above example, then this method provides a means to describe the failure in nerd-speak. This is done at `LogLevel.critical` by default, since no corrective guidance can be offered to an user/administrator, and the impact of the condition is unknown.

Parameters
staticMessage:`str` | Undocumented
level:`LogLevel` | a `LogLevel` to use.
format | a message format using new-style (PEP 3101) formatting. The logging event (which is a `dict`) is used to render this format string.

Returns
`ContextManager[None]` | A context manager which does not return a value, but will always exit from exceptions.

See Also
`Logger.failure`

def failuresHandled(self, format: `str`, level: `LogLevel` = LogLevel.critical, **kwargs: `object`) -> `ContextManager[Operation]`: (source)

Run some application code, logging a failure and emitting a traceback in the event that any of it fails, but continuing on. For example:

        log = Logger(...)

        def frameworkCode() -> None:
            with log.failuresHandled("While frobbing {knob}:", knob=knob) as op:
                frob(knob)
            if op.succeeded:
                log.info("frobbed {knob} successfully", knob=knob)

This method is meant to capture unexpected exceptions from application code; an exception that is caught and handled somehow should be logged, if appropriate, via `Logger.error` instead. If some unknown exception occurs and your code doesn't know how to handle it, as in the above example, then this method provides a means to describe the failure. This is done at `LogLevel.critical` by default, since no corrective guidance can be offered to an user/administrator, and the impact of the condition is unknown.

Parameters
format:`str` | a message format using new-style (PEP 3101) formatting. The logging event (which is a `dict`) is used to render this format string.
level:`LogLevel` | a `LogLevel` to use.
**kwargs:`object` | additional key/value pairs to include in the event, if it is emitted. Note that values which are later mutated may result in non-deterministic behavior from observers that schedule work for later execution.

Returns
`ContextManager[Operation]` | A context manager which yields an `Operation` which will have either its `succeeded` or `failed` attribute set to `True` upon completion of the code within the code within the `with` block.

See Also
`Logger.failure`
`Logger.failureHandler`

def info(self, format: `str | None` = None, **kwargs: `object`): (source)

Emit a log event at log level `LogLevel.info`.

Parameters
format:`str | None` | a message format using new-style (PEP 3101) formatting. The logging event (which is a `dict`) is used to render this format string.
**kwargs:`object` | additional key/value pairs to include in the event. Note that values which are later mutated may result in non-deterministic behavior from observers that schedule work for later execution.

def warn(self, format: `str | None` = None, **kwargs: `object`): (source)

Emit a log event at log level `LogLevel.warn`.

Parameters
format:`str | None` | a message format using new-style (PEP 3101) formatting. The logging event (which is a `dict`) is used to render this format string.
**kwargs:`object` | additional key/value pairs to include in the event. Note that values which are later mutated may result in non-deterministic behavior from observers that schedule work for later execution.

namespace = (source)

the namespace for this logger

observer: `ILogObserver` = (source)

The observer that this logger will send events to.

source = (source)

The object which is emitting events via this logger

@staticmethod
def _namespaceFromCallingContext() -> `str`: (source)

Derive a namespace from the module containing the caller's caller.

Returns
`str` | the fully qualified python name of a module.