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?

Dan
  • 1,575
  • 1
  • 11
  • 17
  • Logging has a built in function that should help with this. https://docs.python.org/3/library/logging.html#logging.Logger.propagate – Glazbee Oct 17 '19 at 10:56
  • can you give an example? just to clarify, i cannot change the code inside the imported module. – Dan Oct 17 '19 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. – Neraste Oct 17 '19 at 11:36
  • @Dan I apologise, it didn't have the expected result during testing. Have you considered using a decorator function? – Glazbee Oct 17 '19 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 ? – Marius Mucenicu Oct 22 '19 at 06:05
  • @Marius Mucenicu I didn't find an answer, I've assumed it's not possible based on Neraste's answer. – Dan Oct 22 '19 at 08:22
  • @Dan...well... I can show you a way you can exclude logging messages from a particular function if you're still interested, please provide a more detailed description of how your `logging` is configured. – Marius Mucenicu Oct 22 '19 at 08:35
  • @Marius Mucenicu I've looked a bit further and I think I've found a way of doing it based on https://stackoverflow.com/questions/879732/logging-with-filters... I'll see if I can answer my own question – Dan Oct 22 '19 at 08:56

1 Answers1

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!
Dan
  • 1,575
  • 1
  • 11
  • 17