【问题标题】:Logger to not show INFO from external libaries记录器不显示来自外部库的信息
【发布时间】:2017-02-15 08:40:53
【问题描述】:

我希望记录器从我的所有代码中打印 INFO 消息,而不是从 3rd 方库中。这在多个地方进行了讨论,但建议的解决方案对我不起作用。这是我模拟的外部库,extlib.py

#!/usr/bin/env python3
from logging import info

def f():
    info("i am extlib f()")

我的模块:

#!/usr/bin/env python3
import logging
from logging import info
import extlib

logging.basicConfig(level=logging.INFO)
info("I am mymodule")
extlib.f()

输出:

INFO:root:我是我的模块

INFO:root:我是 extlib f()

我尝试只为本地模块启用 INFO:

#!/usr/bin/env python3
import logging
from logging import info
import extlib

logging.getLogger(__name__).setLevel(logging.INFO)
info("I am mymodule")
extlib.f()

输出:无

期望的输出:

INFO:root:我是我的模块

我做错了什么?

【问题讨论】:

    标签: python logging


    【解决方案1】:

    问题是他们没有使用外部库中的记录器类。如果是,那么您可以将其过滤掉。我不确定您是否可以阻止他们记录信息,因为他们正在使用 info 函数调用。不过,这里有一个解决方法。

    Suppressing output of module calling outside library

    更新:

    这里是你如何做记录器

    import logging
    
    # create logger
    logger = logging.getLogger('simple_example')
    logger.setLevel(logging.DEBUG)
    
    # create console handler and set level to debug
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    
    # create formatter
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    
    # add formatter to ch
    ch.setFormatter(formatter)
    
    # add ch to logger
    logger.addHandler(ch)
    
    # 'application' code
    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')
    

    【讨论】:

    • 1.问题是关于日志库,而您的链接指向输出重定向。 2. “他们”正在使用日志库,在我的示例中,“他们”是extlib.py,它显然使用了日志库。
    • 是吗?我明白那个?他们正在使用记录器库中的函数,而不是使用记录器库中的记录器类。这就是问题所在......
    • 另一个想法,您是否在调用他们的代码之前尝试更改日志记录级别?这可能会奏效。现在没有机会测试它。 basicConfig无法调用,但可以直接更改级别
    • 我没有意识到它可以用作对象。我尝试将其用作对象:logger = logging.getLogger(__name__); logger.setLevel(logging.INFO);logger.info("I am mymodule") 但我仍然没有看到任何输出。
    • 哦,我还没有深入到高级教程。我认为基本用法足以让我开始,但最终我手上完全转储了 SQLAlchemy 日志,顺便说一句,它确实使用了日志记录类。
    猜你喜欢
    • 1970-01-01
    • 2021-09-20
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多