Révision 85fba042
Ajouté par Benjamin Dauvergne il y a presque 11 ans
entrouvert/logging/decorators.py | ||
---|---|---|
1 |
import logging |
|
2 |
import time |
|
3 |
from functools import wraps |
|
4 |
|
|
5 |
__all__ = [ 'timing' ] |
|
6 |
|
|
7 |
class TimingDecorator(object): |
|
8 |
def __init__(self, *args_to_report, **kwargs): |
|
9 |
if kwargs.get('logger'): |
|
10 |
self.logger = logging.getLogger(kwargs.get('logger')) |
|
11 |
else: |
|
12 |
self.logger = logging.getLogger(__name__) |
|
13 |
self.args_to_report = args_to_report |
|
14 |
|
|
15 |
def __call__(self, func): |
|
16 |
if hasattr(func, '__module__'): # functions |
|
17 |
name = '{0}.{1}'.format(func.__name__, func.__module__) |
|
18 |
else: # methods |
|
19 |
name = '{0}.{1}.{2}'.format(func.__name__, |
|
20 |
func.__objclass__.__name__, func.__objclass__.__module__) |
|
21 |
@wraps(func) |
|
22 |
def f(*args, **kwargs): |
|
23 |
print 'coin' |
|
24 |
a = [] |
|
25 |
for i in self.args_to_report: |
|
26 |
a.append(args[i]) |
|
27 |
a = unicode(a) |
|
28 |
entry = time.time() |
|
29 |
self.logger.debug('%(name)s args: %(args)s entry: %(entry)s', dict( |
|
30 |
name=name, args=a, entry=entry)) |
|
31 |
try: |
|
32 |
result = func(*args, **kwargs) |
|
33 |
finally: |
|
34 |
exit = time.time() |
|
35 |
duration = exit - entry |
|
36 |
self.logger.debug('%(name)s args: %(args)s exit: %(exit)s duration: %(duration)s', dict( |
|
37 |
name=name, args=a, exit=exit, duration=duration)) |
|
38 |
return result |
|
39 |
return f |
|
40 |
|
|
41 |
timing = TimingDecorator |
Formats disponibles : Unified diff
logging: add a decorator to log timing of functions or methods
Use it like that: