Better way to log method calls in Python?

前端 未结 5 1049
醉梦人生
醉梦人生 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:04

    This might be overkill, but there is a trace function facility that will inform you of a great deal of activity within your program:

    import sys
    
    def trace(frame, event, arg):
        if event == "call":
            filename = frame.f_code.co_filename
            if filename == "path/to/myfile.py":
                lineno = frame.f_lineno
                # Here I'm printing the file and line number, 
                # but you can examine the frame, locals, etc too.
                print "%s @ %s" % (filename, lineno)
        return trace
    
    sys.settrace(trace)
    call_my_function()
    sys.settrace(None)
    

提交回复
热议问题