【问题标题】:Why set logging level for each module won't show logs in my code?为什么为每个模块设置日志级别不会在我的代码中显示日志?
【发布时间】:2020-10-10 09:42:55
【问题描述】:

一些简单的代码来说明我的问题:

/src
   -- t1.py
   -- t2.py
   -- test.py

test.py

import logging
import t1
import t2

def main():
    # I need to set logging level for each module, so can't call logging.basicConfig
    # logging.basicConfig(level=logging.DEBUG)
    t1.foo()
    t2.foo2()

if __name__ == "__main__":
    main()

t1.py

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


def foo():
    logger.info('foo log message')

t2.py

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


def foo2():
    logger.info('foo2 log message')

当我运行python3 test.py 时,我不会得到日志。但是如果我在 test.py 中调用logging.basicConfig(level=logging.DEBUG),我会得到日志。

那我做错了什么?

---更新---

我可以添加到我得到的答案是根记录器的默认级别是“警告”。所以我没有得到任何输出。

【问题讨论】:

  • 您仍然可以使用 test.py 中的 logging.basicConfig 来创建标准处理程序。 logger.setLevel 除此之外还可以在模块文件中使用。
  • @Wups 确实!!谢谢!!

标签: python python-3.x logging


【解决方案1】:

logger.setLevel(logging.DEBUG) 设置此记录器可处理的消息级别。

logging.basicConfig(level=logging.DEBUG) 执行more than that。它为根记录器创建一个处理程序,将记录记录打印到标准输出。

来自cookbook的一个例子:

console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

【讨论】:

  • 所以你的意思是我还需要在每个模块中创建句柄?
  • 日志记录从每个模块(在您的情况下)中的记录器传播到父记录器,最后传播到根记录器。您需要将处理程序添加到根记录器。 docs.python.org/3/howto/…
  • 我的意思是,您可以为每个记录器添加一个处理程序,但通常向根记录器添加一个就足够了。
  • 您好,我是 python 日志记录的新手,您可以编辑您的答案以显示如何在 test.py 中获取根记录器并在我的代码中添加处理程序吗?谢谢!
  • 所以 logging.getLogger('') 来获取根记录器。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
相关资源
最近更新 更多