Better way to log method calls in Python?

前端 未结 5 1042
醉梦人生
醉梦人生 2020-12-14 08:35

We can code out some sort of logging decorator to echo function/method calls like the following:

def log(fn):
    ...

@log
def foo():
    ...

class Foo(obj         


        
5条回答
  •  抹茶落季
    2020-12-14 09:18

    I'm not sure what your use case is for this, but generally, I would think more about what exactly is the problem that you're trying to solve.

    That said, here's an example that might do what you want but without a decorator:

    #!/usr/bin/env python
    import inspect
    
    
    class Foo(object):
    
        def foo(self):
            pass
    
        def bar(self, a, b):
            pass
    
        def foobar(self, x, y, z):
            pass
    
        def __getattribute__(self, name):
            returned = object.__getattribute__(self, name)
            if inspect.isfunction(returned) or inspect.ismethod(returned):
                print 'called ', returned.__name__
            return returned
    
    
    if __name__ == '__main__':
        a = Foo()
        a.foo()
        a.bar(1, 2)
        a.foobar(1, 2, 3)
    

    Output:

    called  foo
    called  bar
    called  foobar
    

提交回复
热议问题