Welcome, guest | Sign In | My Account | Store | Cart

Use a function decorator to tell when and how a function should be logged. All kinds of things can be logged automatically, including the function arguments and (theoretically) even the stack.

Python, 53 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/python2.4

"""Demonstrate function decorators."""

import sys
import time


def logged(when):

    """Log every invocation of the function.

    when -- This should be "pre" or "post".  If "post", then I'll also time
        the function, which may be useful for profiling.

    """

    def log(f, *args, **kargs):
        print >> sys.stderr, """\
Called:
  function: %s
  args: %s
  kargs: %s""" % (`f`, `args`, `kargs`)

    def pre_logged(f):
        def wrapper(*args, **kargs):
            log(f, *args, **kargs)
            return f(*args, **kargs)
        return wrapper

    def post_logged(f):
        def wrapper(*args, **kargs):
            start = time.time()
            try:
                return f(*args, **kargs)
            finally:
                log(f, *args, **kargs)
                print >> sys.stderr, """\
  time delta: %s""" % (time.time() - start)
        return wrapper

    try:
        return {"pre": pre_logged, "post": post_logged}[when]
    except KeyError, e:
        raise ValueError(e)


@logged("post")
def hello(name):
    print "Hello,", name


hello("World!")