Logging decorators in Python

Sep 08, 2009 13:42

I've been doing a lot of debugging lately, and have been using this bit of code to great effect:

from traceback import extract_stack, format_list
ti = 0.0

class rec:
    def __init__(self):
        self._his = []

def __setattr__(self, key, value):
        if key != '_his':
            self._his.append((key, value, ti, extract_stack()[:-1]))
        self ( Read more... )

Leave a comment

Comments 5

(The comment has been removed)

ashamrin September 9 2009, 05:45:03 UTC
No, class decorators were added in Python 2.6:
http://docs.python.org/whatsnew/2.6.html#pep-3129-class-decorators

And on earlier versions you could always just use: SomeClass = some_decorator(SomeClass)

Reply

bramcohen September 9 2009, 06:14:26 UTC
I just ported to Python 3, which fixes that problem

Reply


Would be easy if primitive methods could be hooked... elitak September 21 2009, 22:46:02 UTC
I spent a good deal of time looking into this, because it interested me and I thought I had an easy and clean solution using AOP. Well, it turned out to be neither clean nor easy, but I did learn from it at least ( ... )

Reply

Re: Would be easy if primitive methods could be hooked... bramcohen September 21 2009, 23:02:18 UTC
I've got something working fairly well now. I did it by wrapping everything, rather than trying to modify extant objects. The main subtlety has to do with method invocations. What I wound up doing there is having methods which get returned from __getattr__ get replaced with new functions which call the function which the method is a wrapper of, and pass the wrapper in as the self. I'm gonna make it all public at some point, along with a bunch of other stuff, but other priorities have bubbled up at the moment.

Reply

Re: Would be easy if primitive methods could be hooked... elitak September 22 2009, 01:01:34 UTC
What you're describing there with instance methods is exactly what Aspect Oriented Programming and the aspects lib at http://www.cs.tut.fi/~ask/aspects/index.shtml are designed to deal with. You should definitely have a look at it. It handles the creation of that "middleman" function you mention and allows you to write the wrappers as coroutines, which gives you a lot more control over the execution of the underlying method. I've been using the library a lot since I discovered it. I don't know how familiar you are with AOP, but I think the paradigm lends itself very well to python.

Reply


Leave a comment

Up