gpt4 book ai didi

使用多个模块的 python 日志记录不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:52 34 4
gpt4 key购买 nike

我创建了一些 Python 文件,将我的功能分开一些,以便于工作/修复。所有文件都在一个目录中。该结构可能会分解为如下内容:

  • a.py(具有基本内容的 A 类)
  • b.py(具有基本内容的 B 类)
  • modA.py(创建一个派生自 A 和 B 的类 C)
  • modB.py(创建一个派生自 A 和 B 的类 D)
  • ...
  • main_a.py(使用 C 类)
  • main_b.py(使用类 D)

每个模块都使用来自 python 的日志记录。为什么如此 - 只写入根记录器消息。而且我没有看到我的错误。

这是一个最小的例子。

a.py

import logging
logger = logging.getLogger(__name__)

class A(object):
def __init__(self):
logger.debug("Instance of A")

b.py

import logging
logger = logging.getLogger(__name__)

class B(object):
def __init__(self):
logger.debug("Instance of B")

ab.py

import a
import b
import logging
logger = logging.getLogger(__name__)

class AB(a.A, b.B):
def __init__(self):
logger.debug("Instance of AB")
a.A.__init__(self)
b.B.__init__(self)

main_one.py

import sys
import ab

import logging
import logging.handlers
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(stream=sys.stderr)
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter('%(name)s: %(message)s'))
logger.addHandler(handler)

logger.warning("The trouble starts")

ab = ab.AB()

我还尝试使用类似 self.logger = logging.getLogger(type(self).__name__) 的方法在每个类基础上进行日志记录,但结果是一样的。那么你们中有人可以指出我在阅读 python 日志记录手册时哪里出错了吗?

TIA。

编辑 1:我的解决方案

感谢@falsetru 和@Jakub M.,使用这两个答案可以得出可行的解决方案。

首先,我将所有内容都放在一个层次结构中。

main_one.py
lib/
__init__.py
ab.py
basic/
__init__.py
a.py
b.py

其次,我将 main_one.py 中的 logger = logging.getLogger(__name__) 更改为 logger = logging.getLogger() (< em>没有根记录器的名称!)。

成功了。

代码片段非常有帮助 on GitHub .

最佳答案

为每个模块执行 print __name__ 并查看实际得到的结果。您应该将您的模块放入适当的目录中,这样 __name__ 就是一个 "period separated hierarchical value" .例如,如果您的文件层次结构如下所示:

main_a.py
libs/
__init__.py
a.py
modA.py

然后 __name__ 您的模块(a.pymodA.py)将是 libs.alibs.modA

The name is potentially a period-separated hierarchical value, like foo.bar.baz (though it could also be just plain foo, for example). Loggers that are further down in the hierarchical list are children of loggers higher up in the list. For example, given a logger with a name of foo, loggers with names of foo.bar, foo.bar.baz, and foo.bam are all descendants of foo. The logger name hierarchy is analogous to the Python package hierarchy, and identical to it if you organise your loggers on a per-module basis using the recommended construction logging.getLogger(name). That’s because in a module, name is the module’s name in the Python package namespace.

关于使用多个模块的 python 日志记录不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17336680/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com