在定义mixin类的文件中,如何使用使用mixin所在文件中的记录器?

2024-10-03 13:25:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在抽象出一段重复的代码,在其中我在许多类中设置了一个记录器

我希望有一个类,其中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属性


Tags: thetoimportselfloggingloggermixindo
1条回答
网友
1楼 · 发布于 2024-10-03 13:25:55

您可以直接使用getLogger根据模块名称获取记录器,而不是在模块中实例化一个全局文件然后尝试访问它。此外,我只需在__init__中执行一次默认设置,而不是在属性中的每个查找中执行:

self._logger = logger or logging.getLogger(self.__class__.__module__)

编辑包含完整的解决方案

完整的mixin loggable.py将是:

import logging


class Loggable:
    """ Mixin to allow instantiation of a class with a logger, or by default use the module logger from that class

    ```
    class MyResource(Logged):
        def do_something(self):
            self.logger.info('write to a logger')

    MyResource().do_something()  # Log statements go to the default logger for the module in which MyResource is a member
    MyResource(logger=logging.getLogger("specific"))  # Log statements go to the specific logger.
    ```
    """

    def __init__(self, *args, logger=None, **kwargs):
        super().__init__(*args, **kwargs)
        self._logger = logger or logging.getLogger(self.__class__.__module__)

    @property
    def logger(self):
        return self._logger

相关问题 更多 >