How can you suppress logging for a block of code in structlog?

93 Views Asked by At

I am writing a test of an error condition, checking that it occurs and is handled. I don't want the test output to be spammed with error messages for errors that have been deliberately provoked and handled. Structlog is being used for all the logging.

How can I temporarily suppress all log output for a block of text, so that logging resumes normally afterwards?

1

There are 1 best solutions below

0
On BEST ANSWER

The simplest approach is to use structlog's capture_logs context manager, which suppresses logging as a side-effect. You can disregard the captured content.

You can wrap it in another context manager with a more explicit name, like this:

from contextlib import contextmanager
from structlog.testing import capture_logs

@contextmanager
def suppress_logging():
    with capture_logs():
        yield

Then, you can use it in your test code:

with suppress_logging():
    make_error_happen()  # no log output
...
make_error_happen()  # log output active again