Applies FunctionLogger to all __getattribute__ calls on a class

PHOTO EMBED

Wed Aug 18 2021 17:05:05 GMT+0000 (Coordinated Universal Time)

Saved by @kenleyarai #python

import logging
from .ReportLogger import FunctionLogger
from .ReportLogger import LoggerString

def log_all_methods(cls):
    """
    Logs all the methods of a class
    """
    logger_string = LoggerString()

    class WrappedClass:

        def __init__(self, *args, **kwargs):

            logging.debug(logger_string.generate_entering_class_string(
                cls, *args, **kwargs))

            self.__instance = cls(*args, **kwargs)

            logging.debug(logger_string.generate_exiting_class_string(
                cls, *args, **kwargs))

        def __getitem__(self, key: str):
            return self.__instance[key]

        def __getattribute__(self, s):
            try:
                x = super(WrappedClass, self).__getattribute__(s)
            except AttributeError:
                pass
            else:
                return x
            x = self.__instance.__getattribute__(s)
            return FunctionLogger(x)


    return WrappedClass
content_copyCOPY