Projet

Général

Profil

« Précédent | Suivant » 

Révision 85fba042

Ajouté par Benjamin Dauvergne il y a presque 11 ans

logging: add a decorator to log timing of functions or methods

Use it like that:

from entrouvert.logging.decorators import timing
@timing(0, 1, logger='timing')
def method(arg0, arg1):
etc...
return arg0
It will output lines to the logger named 'timing' at the DEBUG level::
DEBUG module.method args: [arg0,arg1] entry: 23232.23232323
DEBUG module.method args: [arg0,arg1] exit: 232334.23232323 duration: 232.2323

Voir les différences:

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