Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import functools
- import inspect
- import logging
- import time
- logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
- logger = logging.getLogger(__name__)
- logger.level = logging.DEBUG
- ENABLE_TIMERS = True
- _LOG_STRING = 'Timed function call: %s (%s) with args "%s" took %s seconds'
- def _logging_wrapper(func, func_name, func_file, bind=None):
- @functools.wraps(func)
- def _wrapper(*args, **kwargs):
- if bind:
- func_args = inspect.getcallargs(func, bind, *args, **kwargs)
- start_time = time.clock()
- result = func(bind, *args, **kwargs)
- else:
- func_args = inspect.getcallargs(func, *args, **kwargs)
- start_time = time.clock()
- result = func(*args, **kwargs)
- duration = time.clock() - start_time
- logger.debug(_LOG_STRING % (func_name, func_file, func_args, duration))
- return result
- return _wrapper
- class _DescriptorWrapper(object):
- def __init__(self, func):
- self.func = func
- self.func_file = os.path.join(os.getcwd(), inspect.getfile(self.func))
- self.func_module = inspect.getmodule(self.func).__name__
- def __get__(self, instance, owner):
- func_name = '.'.join((self.func_module, owner.__name__,
- self.func.__name__))
- return _logging_wrapper(self.func, func_name, self.func_file,
- bind=instance)
- def __call__(self, *args, **kwargs):
- func_name = '.'.join((self.func_module, self.func.__name__))
- return _logging_wrapper(self.func, func_name,
- self.func_file)(*args, **kwargs)
- def logexectime(func):
- if not ENABLE_TIMERS or inspect.isbuiltin(func):
- return func
- return functools.wraps(func)(_DescriptorWrapper(func))
- class A(object):
- @logexectime
- def f1(self, a, b):
- return a + b
- @logexectime
- def f2(a, b):
- print a + b
- a = A()
- print a.f1(10, 12)
- f2(45, 12)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement