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

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

    Late answer, but oh well.

    Another solution is that you can create your own formatter with a filter as specified in the docs here. This is a really great feature as you now no longer have to use a helper function (and have to put the helper function everywhere you want the stack trace). Instead, a custom formatted implements it directly into the logs themselves.

    import logging
    class ContextFilter(logging.Filter):
        def __init__(self, trim_amount)
            self.trim_amount = trim_amount
        def filter(self, record):
            import traceback
            record.stack = ''.join(
                str(row) for row in traceback.format_stack()[:-self.trim_amount]
            )
            return True
    
    # Now you can create the logger and apply the filter.
    logger = logging.getLogger(__name__)
    logger.addFilter(ContextFilter(5))
    
    # And then you can directly implement a stack trace in the formatter.    
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s \n %(stack)s')
    

    Note: In the above code I trim the last 5 stack frames. This is just for convenience and so that we don't show stack frames from the python logging package itself.(It also might have to be adjusted for different versions of the logging package)

提交回复
热议问题