使用 LoggerMixin 记录函数名称和对象属性

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

我想要

LoggerMixin
记录

  • 调用其实例的函数的名称 (
    info
    )
  • 属于该函数的对象的属性(
    self.brand
    self.wheel
    )。

我怎样才能实现这个目标?请参阅下面我目前所在的位置:

import logging


class LoggerMixin:
    def log(self):
        logging.basicConfig(level=logging.INFO, format='%(funcName)s-%(message)s')
        return logging.info(f'func name is {self.__class__.__name__}')


class Car(LoggerMixin):
    def __init__(self, brand: str, wheel: int):
        self.brand = brand
        self.wheel = wheel

    def info(self):
        print(f'my brand is {self.brand} and i have {self.wheel} wheel')


obj1 = Car(brand='bmw', wheel=4)
obj1.info()
python python-3.x logging mixins
1个回答
0
投票
  • basicConfig
    可以在类外定义。
  • 您应该向
    __init__()
    添加一个
    LoggerMixin
    方法。
  • 通过调用
    LoggerMixin
    来初始化继承的
    super().__init__()
    对象。
  • logging.info()
    本地调用
    self.logger
    ,以便它正确识别
    funcName

我的建议还有进一步的小改进:

import logging

logging.basicConfig(level=logging.INFO, format='%(funcName)s – %(message)s')


class LoggerMixin:
    def __init__(self):
        self.logger = logging.getLogger()


class Car(LoggerMixin):
    def __init__(self, brand: str, wheel: int):
        super().__init__()

        self.brand = brand
        self.wheel = wheel

    def info(self):
        self.logger.info(f'My brand is {self.brand} and I have {self.wheel} wheel(s)')


obj1 = Car(brand='bmw', wheel=4)
obj1.info()
© www.soinside.com 2019 - 2024. All rights reserved.