Created
February 24, 2021 15:43
-
-
Save aelindeman/a3a68b0fde204192dc7041131a07ae92 to your computer and use it in GitHub Desktop.
Python metaclass that logs calls to methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
from types import FunctionType | |
class MethodCallLoggingMetaclass(type): | |
def __new__(mcs, name, bases, attrs): | |
for attr_name, attr_value in attrs.items(): | |
if isinstance(attr_value, FunctionType): | |
attrs[attr_name] = mcs.log_wrapper(attr_value, name) | |
return super().__new__(mcs, name, bases, attrs) | |
@classmethod | |
def log_wrapper(mcs, func, class_name): | |
def wrapped(*args, **kwargs): | |
logging.debug('%s.%s', class_name, func.__name__) | |
return func(*args, **kwargs) | |
return wrapped |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment