创建一个 mixin 类,向类添加日志记录功能

问题描述 投票:0回答:0

每当从类中调用方法时,mixin 必须记录方法名称及其参数。 这是我的问题(创建一个名为 LoggerMixin 的 mixin,它将日志记录功能添加到类中。每当从类中调用方法时,mixin 必须记录方法名称及其参数。(此练习需要搜索并了解日志记录模块))

 import logging


class LoggerMixin:
    logger = logging.getLogger('__name__')
    logger.setLevel(logging.INFO)

    stream_ha = logging.StreamHandler()
    stream_f = logging.Formatter('%(funcName)s - %(levelname)s - %(message)s')
    stream_ha.setFormatter(stream_f)
    stream_ha.setLevel(logging.INFO)
    logger.addHandler(stream_ha)

    def __init__(self, logger, **kwargs):
        super().__init__(**kwargs)
        self.logger = logger

    def logger(self):
        return self.logger

    class Vehicle:
        def __init__(self, color: str, weight: float, speed: int, wheel: int) -> None:
            self.color = color
            self.weight = weight
            self.wheel = wheel
            self.speed = speed

        def move(self):
            return f"I can move in different ways"


class Car(Vehicle, LoggerMixin):
    def __init__(self, brand: str, **kwargs):
        super().__init__(**kwargs)
        self.brand = brand

    def move(self):
        return f"i can move with {self.wheel} wheel and {self.speed} speed "


class Lamborghini(Car):

    def move(self):
        return f"i can move with {self.wheel} wheel and {self.speed} speed "


class Benz(Car):
    def move(self):
        return f"i can move with {self.wheel} wheel and {self.speed} speed "
python python-3.x logging mixins
© www.soinside.com 2019 - 2024. All rights reserved.