Python-关于登录的问题
我有以下python包结构Python-关于登录的问题,python,logging,Python,Logging,我有以下python包结构 python_logging python_logging __init__.py first_class.py second_class.py run.py 以下是\uuuu init\uuuuuuupy init.py 下面是first_class.py的代码 import logging class FirstClass(object): def __init__(self):
python_logging
python_logging
__init__.py
first_class.py
second_class.py
run.py
以下是
\uuuu init\uuuuuuupy
init.py
下面是first_class.py的代码
import logging
class FirstClass(object):
def __init__(self):
self.current_number = 0
self.logger = logging.getLogger(__name__)
def increment_number(self):
self.current_number += 1
self.logger.warning('Incrementing number!')
self.logger.info('Still incrementing number!!')
下面是second_class.py的代码
class SecondClass(object):
def __init__(self):
self.enabled = False
self.logger = logging.getLogger(__name__)
def enable_system(self):
self.enabled = True
self.logger.warning('Enabling system!')
self.logger.info('Still enabling system!!')
下面是run.py的代码
from LogModule.first_class import FirstClass
from LogModule.second_class import SecondClass
number = FirstClass()
number.increment_number()
system = SecondClass()
system.enable_system()
这是日志文件中的输出
LogModule - INFO - Completed configuring logger()!
LogModule.first_class - WARNING - Incrementing number!
LogModule.first_class - INFO - Still incrementing number!!
LogModule.second_class - WARNING - Enabling system!
LogModule.second_class - INFO - Still enabling system!!
问题:在initpy中初始化文件处理程序时,number.increment\u number()和system.enable\u system()如何写入日志文件?而且这两个类都有不同的getLogger。任何人都可以解释一下,这会很有帮助。每个记录器都有一个父级,在Python中,您可以认为所有记录器都构造成一个“树”。如果将处理程序添加到一个记录器中,其子记录器也将共享这些处理程序。因此,这意味着您不需要为每个记录器创建处理程序,否则在每个记录器上设置处理程序将是重复的和枯燥的 回到您的示例,您的包结构
python\u日志
python_日志
__初始值
头等舱
二等兵
run.py
\uuuu init\uuuuu.py
文件中
#创建记录器
loggers=logging.getLogger(_名称__)
记录器名称为
first_class.py中
self.logger=logging.getLogger(\uuuuu name\uuuuu)
记录器名称为
因此,当您从包或其中一个模块导入时,
第一类.py
中的记录器是中记录器的子级。我知道init.py将始终执行,这是否意味着如果您创建了一次文件处理程序,它就可以被任何记录器使用?(示例self.logger=logging.getLogger(名称)(在上面的示例中为FirstClass和SecondClass)。我的理解是Firstclass中的self.logger无法写入日志文件,因为没有为其创建处理程序。
LogModule - INFO - Completed configuring logger()!
LogModule.first_class - WARNING - Incrementing number!
LogModule.first_class - INFO - Still incrementing number!!
LogModule.second_class - WARNING - Enabling system!
LogModule.second_class - INFO - Still enabling system!!