我有以下 python 包结构。
python_logging
python_logging
__init__.py
first_class.py
second_class.py
run.py
Run Code Online (Sandbox Code Playgroud)
这里是代码 __init__.py
初始化.py
import logging
import logging.config
# Create the Logger
loggers = logging.getLogger(__name__)
loggers.setLevel(logging.DEBUG)
# Create the Handler for logging data to a file
logger_handler = logging.FileHandler(filename='C:\Python\Log\stest.txt')
logger_handler.setLevel(logging.DEBUG)
# Create a Formatter for formatting the log messages
logger_formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
# Add the Formatter to the Handler
logger_handler.setFormatter(logger_formatter)
# Add the Handler to the Logger
loggers.addHandler(logger_handler)
loggers.info('Completed configuring logger()!')
Run Code Online (Sandbox Code Playgroud)
这是 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!!')
Run Code Online (Sandbox Code Playgroud)
这是 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 Code Online (Sandbox Code Playgroud)
这是 run.py 的代码
from LogModule.first_class import FirstClass
from LogModule.second_class import SecondClass
number = FirstClass()
number.increment_number()
system = SecondClass()
system.enable_system()
Run Code Online (Sandbox Code Playgroud)
这是日志文件中的输出
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!!
Run Code Online (Sandbox Code Playgroud)
问题:在init .py中初始化文件处理程序时,number.increment_number() 和 system.enable_system() 如何写入日志文件?这两个类都有不同的 getloggers 。任何人都可以解释一下,它会有所帮助。
liv*_*xin 11
每个记录器都有一个父记录器 - 在 Python 中,您可以认为所有记录器都构造成一棵“树”。如果您将处理程序添加到一个记录器中,则其子记录器也将共享这些处理程序。这意味着您无需为每个记录器创建处理程序 - 否则在每个记录器上设置处理程序将是重复且无聊的。
回到你的样本,你的包结构,
python_logging
python_logging
__init__.py
first_class.py
second_class.py
run.py
Run Code Online (Sandbox Code Playgroud)
在__init__.py文件中,
# Create the Logger
loggers = logging.getLogger(__name__)
Run Code Online (Sandbox Code Playgroud)
记录器名称是<python_logging>.
在first_class.py
self.logger = logging.getLogger(__name__)
Run Code Online (Sandbox Code Playgroud)
记录器名称是<python_logging>.<first_class>.
所以 logger infirst_class.py是 logger in 的子级__init__.py