A memo when I had a hard time getting the class name when logging the method execution time
I want to display the class name and method name when logging with a decorated method to find out which method is running at what time
try1
Try to decorate normally
def deco(func):
def inner(self, *args, **kwargs):
result = func(self, *args, **kwargs)
print 'class: %s, method: %s' % (
func.im_class.__name__,
func.__name__)
#Logging process
return result
return inner
func was passed as a function and didn't have im_class. For this reason, I could get the method name, but not the class name.
try2
Get the class name from self.
def deco(func):
def inner(self, *args, **kwargs):
result = func(self, *args, **kwargs)
print 'class: %s, method: %s' % (
self.__class__.__name__,
func.__name__)
#Logging process
return result
return inner
NG because the subclass name will be returned when inheriting
try3
Decorate the class.
def deco_cls(cls):
def deco_method(func):
def inner(self, *args, **kwargs):
result = func(self, *args, **kwargs)
print 'class: %s, method: %s' % (
cls.__name__,
func.__name__)
#Logging process
return result
return inner
for name, method in cls.__dict__.items():
if name == 'target_func':
setattr(cls, name, deco_method(method))
return cls
It is compared as target_func, but in the version actually used, the target method name was prepared as a tuple and compared. If you want to specify the target method clearly, you can also use the following method.
def deco_cls(cls):
def deco_method(func):
def inner(self, *args, **kwargs):
result = func(self, *args, **kwargs)
print 'class: %s, method: %s' % (
cls.__name__,
func.__name__)
#Logging process
return result
return inner
for name, method in cls.__dict__.items():
if hasattr(method, 'set_logger'):
setattr(cls, name, deco_method(method))
return cls
def set_logger_wrapper(func):
func.set_logger = True
return func
Recommended Posts