Disable logs from imported module using the root logger

Viewed 89

One of Microsoft's presidio-analyzer modules logs with the root logger:

        logging.info(
            "Returning a total of %d recognizers (predefined + custom)", len(to_return)
        )

This particular line will be written millions of times.

I created an issue on GitHub, but in the meantime, is there a way to suppress these logs? I can't access the logger by name, and I can't set the root logger to WARN either because it propagates to all my loggers.

1 Answers

Patch the import of logging in that specific module, like so:

import microsoft_module

microsoft_module.logging = my_fake_logging

Than you can proxy all the calls with the desired level to the actual ligging module.

Note not to patch microsoft_module.logging.info directly, for it will affect all logging, since it's the same module used.

Update: I tried to mess around with the concept a bit, and here's what I came up with:

You can patch the globals in a specific function, that way you can change logging in that specific scope!

x = 5

def g():
    print(x)

g() 

print(g.__globals__)
g.__globals__['x'] = 9

g()

Output:

5
{'__name__': '__main__', '__file__': '/data/user/0/ru.iiec.pydroid3/files/temp_iiec_codefile.py', '__builtins__': <module 'builtins' (built-in)>, '__warningregistry__': {'version': 0}, 'x': 5, 'g': <function g at 0x755125edc0>}
9
Related