0

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?

8
  • Logging has a built in function that should help with this. docs.python.org/3/library/logging.html#logging.Logger.propagate Commented Oct 17, 2019 at 10:56
  • can you give an example? just to clarify, i cannot change the code inside the imported module. Commented Oct 17, 2019 at 11:03
  • I don't think this is possible for a single function. Usually, loggers are defined for an entire module (e.g. logger = logging.getLogger(__name__)) and the logger doesn't know who is calling it. Commented Oct 17, 2019 at 11:36
  • @Dan I apologise, it didn't have the expected result during testing. Have you considered using a decorator function? Commented Oct 17, 2019 at 11:53
  • @Dan did you find a solution or do you still need an answer here? If you do, please provide more information regarding your logging configuration. Do you use a dictConfig ? Do you just use it straight out of the box ? Commented Oct 22, 2019 at 6:05

1 Answer 1

1

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!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.