How to suppress logging.warning from imported module (which uses loguru)

303 Views Asked by At

I am using a function from an imported module within an optimization loop. As a consequence the function gets called 10s or 100s of times. Since this is an optimization, sometimes the test parameters will cause a warning to be raised in the function being called (for example, because they are below a threshold value). I'm ok with these warnings, but I don't need them to appear 100s of times in my terminal. I am fine with manually checking the resulting parameters after the optimization has completed.

Is there some kind context manager that can be used to suppress any calls to logger.warning just for this function call?

An extra wrinkle is that the imported module is using loguru for logging. I'm not sure if that necessitates a different solution or not.

1

There are 1 best solutions below

0
Dave On

You can use loguru.logger.disable(..) for this:

https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.disable

It's relatively straightforward to make this into a context manager. Something like:

@contextmanager
def disabling_loguru(name):
    loguru.logger.disable(name)
    try:
        yield
    finally:
        loguru.logger.enable(name)

You can then decorate your test function like this:

@loguru_disable("noisy_module")
def my_test():
    ...