views:

408

answers:

2

Hello, i have to get static information from one 'module' to another. I'm trying to write logger with information about code place from where we're logging. For example, in some file:

LogObject.Log('Describe error', STATIC_INFORMATION)

Static information is class name, file name and function name. I get it from this:

__file__ 
self.__class__.__name__ 
sys._getframe().f_code.co_name

But i don't want to write this variables during logging. Can i create some function and call it. For example:

LogObject.Log('Describe error', someFunction())

How can i use it for getting static information?

+2  A: 

First, please use lower-case names for objects and methods. Only use UpperCase Names for Class definitions.

More importantly, you want a clever introspective function in every class, it appears.

class Loggable( object ):
    def identification( self ):
        return self.__class__.__module__, self.__class__.__name__, sys._getframe().f_code.co_name

class ARealClass( Loggable ):
    def someFunction( self ):
        logger.info( "Some Message from %r", self. identification() )

If all of your classes are subclasses of Loggable, you'll inherit this identification function in all classes.

S.Lott
Thanks for your reply. >If all of your classes are subclasses of Loggable.No, they aren't. If i'll create class Loggable in other module (file) the data which it returns will not be that what i need. Or i didn't understand?
Ockonal
Have you tried it? If each class is a subclass of Loggable, each class will produce proper values for each object of the class. It will work in multiple files. Try it.
S.Lott
Fixed it to use __module__, which is correct.
S.Lott
I shouldn't inherit all my classes from logger. I have another structure of my app.
Ockonal
That's what mixins are for. Your classes can inherit from more than one thing - so you can do class MyClass(Loggable, MySuperClass) and you will inherit both the loggable bits and your own stuff.
Daniel Roseman
Or, replace `object` with `Loggable`. If you aren't subclassing object, you should be.
S.Lott
+3  A: 

I don't think "static" is the world you're looking for. If I understand you correctly, you want to write a function that will return the filename, class name and method name of the caller.

Basically, you should use sys._getframe(1) to access the previous frame, and work from there.

Example:

def codeinfo():
    import sys
    f = sys._getframe(1)

    filename = f.f_code.co_filename
    classname = ''

    if 'self' in f.f_locals:
        classname = f.f_locals['self'].__class__.__name__

    funcname = f.f_code.co_name

    return "filename: %s\nclass: %s\nfunc: %s" % (filename, classname, funcname)

Then from a method somewhere you can write

logger.info("Some message \n %s" % codeinfo())
itsadok
Thanks, but what about function name?
Ockonal
Added. This is not very good code, though. I'll try to clean it up when I have time.
itsadok
Thanks anywhere, your code works fine.
Ockonal