python - 让父类使用子类记录器名称

标签 python python-3.x

我正在尝试设置一些日志记录,但遇到了问题。每当子类使用父类函数时,都会使用父类函数记录器名称而不是子类的记录器名称。

假设我有以下两个类:

家长类:

import logging
logger = logging.getLogger('ParentClass')

class ParentClass:
    def __init___(self):
        logger.info('This is inside ParentClass')

child 类:
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)

我正在寻找的是 __init__ 调用 ChildClass 在 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 的情况下,有没有办法做到这一点?

最佳答案

基于sureshvv 的帖子,我发现将其放入__init__ 很有帮助我的父类的方法:

self.log = logging.getLogger(self.__class__.__name__)

然后,子类可以使用 self.log 登录并拥有 %(name)s日志格式中的标记正确显示子类名称,而不是父类名称(如果您将 __name__ 传递给 getLogger() 会发生这种情况。)

关于python - 让父类使用子类记录器名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32233403/

相关文章:

python - UnicodeEncodeError : 'utf-8' codec can't encode characters in position 0-15: surrogates not allowed

python - 如何在 Python 中模拟 Firefox "Save File"-> OK

Python3 为 PyPi 准备包,不包括子模块

python - 如何从 Discord API (URL) 获取用户状态

python - Airflow 在 Python 运算符之间传递数据帧

经过太多的划分后,Python 将变为 0.0

python-3.x - 无法在python 3上将复杂转换为 float

python-3.x - 如何在 Python Google Cloud Function 中返回特定状态

python - 创建新的 TemporaryDirectory 对象不会创建目录

python - 在适用于 Python 的 App Engine 中,是否可以保留一个嵌套在其中的另一个对象的类?