Search code examples
python-3.xstructlog

How to set log level with structlog when not using event parameter?


The idiomatic way (I think) to create a logger in structlog that only prints up to a certain log level is to use the following:

        wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),

This works fine, but it breaks with the following pattern:

                l = logger.bind(event="get_tar", key=value)
                l.info(status="download_start")
                buf = f.read()
                l.info(status="download_finish")

by default, when using the logfmt format -- structlog will print the "message" as the event key, so I just like to set it directly.

Anyways, this breaks though b/c under the hood make_filtering_bound_logger calls this:

    def make_method(level: int) -> Callable[..., Any]:
        if level < min_level:
            return _nop

        name = _LEVEL_TO_NAME[level]

        def meth(self: Any, event: str, **kw: Any) -> Any:
            return self._proxy_to_logger(name, event, **kw)

        meth.__name__ = name

        return meth

which requires an event kwarg to exist. Is there a workaround?


Solution

  • event is the only (reasonable :)) key that cannot be bound – it’s always the log message. That’s not a matter of make_… but all structlog internals.

    You can get something similar-ish by renaming a key-value pair using the EventRenamer processor.

    See also https://github.com/hynek/structlog/issues/35

    It’s good you brought this up, I’m currently rewriting the docs and am looking for common recipes.