smart logging and the "inspect" module ...

George Sakkis gsakkis at rutgers.edu
Sat May 28 12:09:43 EDT 2005


"Darran Edmundson" wrote:
> I was playing around with the inspect module the other day
> trying to write a quick and dirty "smart" logger.  By this I mean
> that writing a message to the global log would also yield some
> info about the calling scope.  If you look at my function "test"
> below, I'd ideally like log messages:
>
> foo.py:test, "message 1"
> foo.py:Foo.__init__, "message 2"
> foo.py:Foo.bar, "message 3"
>
> For the life of me I can't figure out how to get this info without
> resorting to ridiculous things like parsing the source code (available
> via inspect.stack.
>
> Any help would be much appreciated - my unit tests are failing
> on this at the moment ;-)
>
> Cheers,
> Darran.

Unfortunately introspection gives access to frame and code objects, but
not to the callable objects (functions, methods, builtins); I think the
reason is that code objects can be shared for different callables.
Also, even the function name and the line number are misleading if
there is an alias (e.g. baz = bar). By the way, here's an alternative
that doesn't use inspect.

import sys

class Log:
    def write(self,message):
        frame = sys._getframe(1)
        code = frame.f_code
        print "%s:%d:%s, %s" % (code.co_filename, frame.f_lineno,
                                code.co_name, message)


There's a logging module in the standard library btw; make sure you
check it out before going on and extending the quick and dirty logger.

Regards,
George




More information about the Python-list mailing list