最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Filtering logging of class at runtime - Stack Overflow

programmeradmin6浏览0评论

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?

Share Improve this question asked Mar 26 at 10:43 probablyjgprobablyjg 331 silver badge4 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You'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.

发布评论

评论列表(0)

  1. 暂无评论