Skip to content

Instantly share code, notes, and snippets.

@aelindeman
Created February 24, 2021 15:43
Show Gist options
  • Save aelindeman/a3a68b0fde204192dc7041131a07ae92 to your computer and use it in GitHub Desktop.
Save aelindeman/a3a68b0fde204192dc7041131a07ae92 to your computer and use it in GitHub Desktop.
Python metaclass that logs calls to methods
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