py.log using decorators for DRY

Y

yoda

I'm using py.log for logging and I find that I end up having the
following pattern emerge within my code (influenced by
http://agiletesting.blogspot.com/2005/06/keyword-based-logging-with-py-library.html):


def foo(**kwargs):
log.foo(kwargs)
#body form

This led me to believe that I could simplify that pattern with the
following idiom :


def logit (fn):
'''
decorator to enable logging of all tagged methods
'''
def decorator (**kwargs):
# call a method named fn.func_name on log with kwargs
#should be something like: log.func_name (kwargs)

return decorator


I can then do add @logit to all my existing methods via a script
(there's a truck load of methods to tag):


@logit
def oldfoo () : pass


My question is in regards to the body form in the decorator. How do I
call that method on the log object at runtime?

(ps. I hope my question is clear $)
 
A

Alex Martelli

yoda said:
I'm using py.log for logging and I find that I end up having the following
pattern emerge within my code (influenced by
http://agiletesting.blogspot.com/2005/06/keyword-based-logging-with-py-lib
rary.html):

def foo(**kwargs):
log.foo(kwargs)
#body form

This led me to believe that I could simplify that pattern with the
following idiom :


def logit (fn):
'''
decorator to enable logging of all tagged methods
'''
def decorator (**kwargs):
# call a method named fn.func_name on log with kwargs
#should be something like: log.func_name (kwargs)

return decorator

Assuming the attributes of object 'log' don't change at runtime (i.e.,
you're OK with early binding), I'd code:

def logit(fn):
method = getattr(log, fn.func_name)
def callit(**kwargs): return method(kwargs)
return callit

If you need to do late binding instead, you can move the getattr to
inside the body of callit.


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top