Search code examples
pythonloggingstructlog

Wrap "py.warnings" logger with structlog to add processors


I have a custom logger including processors, handlers etc. . I would like to wrap the "py.warnings" logger which I understand is used by the warnings so that my processors are 'injected'. However, running the following code does not change anything to the warning that is printed to the console.


import logging
import structlog
import warnings

structlog.wrap_logger(
    logging.getLogger("py.warnings"),
    # processors etc. ...
)

warnings.warn("abc")

Solution

  • This is not gonna work like this. structlog.wrap_logger() is specifically made such that it has no side-effects and you have to use its return value for logging, to use structlog.

    You will have to configure logging to use structlog which is documented here. In a nutshell, structlog comes with a logging-style formatter that allows you to use structlog to format all logging entries with a dedicated processor chain.

    Don't forget to call logging.captureWarnings(True) to integrate logging (and structlog) with the warnings module - relevant python docs.