我正在抽象出一段重复的代码,在其中我在许多类中设置了一个记录器
我希望有一个类,其中mixin允许我使用logger对象实例化该类,或者使用该类的module中的默认模块
我会这样使用它:
import logging
from .mixin import LoggerMixin
resource_module_logger = logging.getLogger(__name__)
class MyResource(LoggerMixin):
""" Instantiate this class to do something.
If instantiated with a custom logger, then all log outputs will go to that. Otherwise, they'll go to resource_module_logger
```
MyResource().do_something() # Does something while logging to resource module logger.
MyResource(logger=logging.getLogger("specific")) # does something while logging to a specific logger.
```
"""
def do_something(self):
self.logger.info("This message will go to the default module level logger, unless a custom logger was specified at instantiation")
到目前为止,我掌握的信息是:
import logging
this_is_not_the_logger_im_looking_for = logging.getLogger(__name__)
class LoggerMixin:
def __init__(self, *args, logger=None, **kwargs):
self._logger = logger
super().__init__(*args, **kwargs)
@property
def logger(self):
# How do I get the resource module logger for the MyResource class which this is mixed into???
resource_module_logger = ?????????????
return self._logger or resource_module_logger
问题
是否有可能从mixin中获取该记录器,从而将其完全抽象出来(如果是,如何提取?),或者我必须为每个类重写logger
属性
您可以直接使用
getLogger
根据模块名称获取记录器,而不是在模块中实例化一个全局文件然后尝试访问它。此外,我只需在__init__
中执行一次默认设置,而不是在属性中的每个查找中执行:编辑包含完整的解决方案
完整的mixin
loggable.py
将是:相关问题 更多 >
编程相关推荐