【发布时间】:2015-11-20 21:26:03
【问题描述】:
我正在尝试设置一些日志记录,但遇到了问题。每当子类使用父类函数时,都会使用父类函数记录器名称而不是子类的记录器名称。
假设我有以下两个类:
父类:
import logging
logger = logging.getLogger('ParentClass')
class ParentClass:
def __init___(self):
logger.info('This is inside ParentClass')
儿童班:
import logging
logger = logging.getLogger('ChildClass')
class ChildClass(ParentClass):
def foo(self):
logger.info('This is inside ChildClass')
然后我运行以下脚本:
import logging
import ParentClass
import ChildClass
# Pretend I set up logging to "example.log"
foo1 = ParentClass.ParentClass()
foo2 = ChildClass.ChildClass()
foo2.foo()
我的日志文件最终看起来像:
INFO:ParentClass:This is inside ParentClass #(<-- this comes from foo1 init)
INFO:ParentClass:This is inside ParentClass #(<-- this comes from foo2 init)
INFO:ChildClass:This is inside ChildClass #(<-- this comes from foo2 foo)
我正在寻找的是对 ChildClass 的 __init__ 调用,以便像这样在 ChildClass 记录器下登录:
INFO:ParentClass:This is inside ParentClass #(<-- this comes from foo1 init)
INFO:ChildClass:This is inside ParentClass #(<-- this comes from foo2 init)
INFO:ChildClass:This is inside ChildClass #(<-- this comes from foo2 foo)
在不将我要使用的记录器的名称传递给 ParentClass 的情况下,是否可以这样做?
【问题讨论】:
-
所以我必须在子类中设置_init_,然后像这样显式调用它? 编辑这种方法不起作用,我仍然在日志文件中得到相同的输出
标签: python python-3.x