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

前端 未结 8 1140
情深已故
情深已故 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:55

    Here is an example that i hope it can help you:

    import inspect
    import logging
    
    logging.basicConfig(
        format = "%(levelname) -10s %(asctime)s %(message)s",
        level = logging.DEBUG
    )
    
    def test():
    
        caller_list = []
        frame = inspect.currentframe()
        this_frame = frame  # Save current frame.
    
        while frame.f_back:
            caller_list.append('{0}()'.format(frame.f_code.co_name))
            frame = frame.f_back
    
        caller_line = this_frame.f_back.f_lineno
        callers =  '/'.join(reversed(caller_list))
    
        logging.info('Line {0} : {1}'.format(caller_line, callers))
    
    def foo():
        test()
    
    def bar():
        foo()
    
    bar()
    

    Result:

    INFO       2011-02-23 17:03:26,426 Line 28 : bar()/foo()/test()
    

提交回复
热议问题