How can I log current line, and stack info with Python?

前端 未结 8 1352
情深已故
情深已故 2021-02-02 11:01

I have logging function as follows.

logging.basicConfig(
    filename = fileName,
    format = \"%(levelname) -10s %(asctime)s %(message)s\",
    level = logging         


        
8条回答
  •  轮回少年
    2021-02-02 11:32

    This is based on @mouad's answer but made more useful (IMO) by including at each level the filename (but not its full path) and line number of the call stack, and by leaving the stack in most-recently-called-from (i.e. NOT reversed) order because that's the way I want to read it :-)

    Each entry has file:line:func() which is the same sequence as the normal stacktrace, but all on the same line so much more compact.

    import inspect
    
    def callers(self):
        caller_list = []
        frame = inspect.currentframe()
        while frame.f_back:
            caller_list.append('{2}:{1}:{0}()'.format(frame.f_code.co_name,frame.f_lineno,frame.f_code.co_filename.split("\\")[-1]))
            frame = frame.f_back
        callers =  ' <= '.join(caller_list)
        return callers
    

    You may need to add an extra f_back if you have any intervening calls to produce the log text.

            frame = inspect.currentframe().f_back
    

    Produces output like this:

    file2.py:620:func1() <= file3.py:211:func2() <= file3.py:201:func3() <= main.py:795:func4() <= file4.py:295:run() <= main.py:881:main()
    

    I only need this stacktrace in two key functions, so I add the output of callers into the text in the logger.debug() call, like htis:

    logger.debug("\nWIRE: justdoit request -----\n"+callers()+"\n\n")
    

提交回复
热议问题