Dan
Dan

Reputation: 1587

python logging: disable messages from specific imported function

I know how to suppress log messages up to a certain log level from an imported module:

import logging
logging.getLogger("module_name").setLevel(logging.WARNING)

I want to know if it's possible to suppress log messages from only a specific function/class in an imported module (and keep all other messages in the module).

I tried this:

logging.getLogger("module_name.function_name").setLevel(logging.WARNING)

but it didn't work. Is it possible?

Upvotes: 0

Views: 1146

Answers (1)

Dan
Dan

Reputation: 1587

I came up with this in the end based on logging with filters:

Contents of my_module.py:

import logging

logger = logging.getLogger(__name__)


def func1():
    logger.debug('Running func1!')


def func2():
    logger.debug('Running func2!')

I want to ignore any messages from func2, but keep any messages from func1.

Contents of main.py:

import logging

import my_module

logging.basicConfig(level=logging.DEBUG)


class IgnoreFunc2(logging.Filter):
    def filter(self, record):
        return not record.funcName == 'func2'


# this relies on knowing the variable name in my_module
my_module.logger.addFilter(IgnoreFunc2())


def main():
    my_module.func1()
    my_module.func2()


if __name__ == '__main__':
    main()

Output:

DEBUG:my_module:Running func1!

Upvotes: 1

Related Questions