I have a class in a module:
# foo.py
import logging
class Foo:
def __init__(self):
self.logger = logging.getLogger(__name__)
self.logger.info("Init successful")
and a script that utilises this class, attempting to filter out the logger in Foo
# bar.py
import logging
from foo import Foo
logging.basicConfig(level=logging.Info)
logger = logging.getLogger(__name__)
logger.addFilter(logging.Filter(__name__))
logger.info("Started script")
foo = Foo()
This doesn't work, is there a way to filter out the logger in Foo
?
I have a class in a module:
# foo.py
import logging
class Foo:
def __init__(self):
self.logger = logging.getLogger(__name__)
self.logger.info("Init successful")
and a script that utilises this class, attempting to filter out the logger in Foo
# bar.py
import logging
from foo import Foo
logging.basicConfig(level=logging.Info)
logger = logging.getLogger(__name__)
logger.addFilter(logging.Filter(__name__))
logger.info("Started script")
foo = Foo()
This doesn't work, is there a way to filter out the logger in Foo
?
1 Answer
Reset to default 1You're creating two loggers, named bar
and foo
, and adding a filter to the bar
logger, but logging from the logger in foo
, which has no filter. By the way, creating loggers as attributes of class instances is an anti-pattern, see this part in the logging documentation. Also, since you're passing in __name__
to the filter in bar.py
, the name you're passing will be bar
. I assume you wanted it to filter out foo
?
It's a lot simpler to just have logger = logging.getLogger('__name__')
in each module and then you can turn on and off verbosity flexibly, without necessarily needing to use filters.