Showing the right funcName when wrapping logger functionality in a custom class

前端 未结 8 1888
你的背包
你的背包 2021-02-01 16:31

This is the formatting string that I am using for logging:

\'%(asctime)s - %(levelname)-10s - %(funcName)s - %(message)s\'

But to show the logg

8条回答
  •  名媛妹妹
    2021-02-01 16:47

    Essentially, the code to blame lies in the Logger class:

    This method

    def findCaller(self):
        """
        Find the stack frame of the caller so that we can note the source
        file name, line number and function name.
        """
        f = currentframe()
        #On some versions of IronPython, currentframe() returns None if
        #IronPython isn't run with -X:Frames.
        if f is not None:
            f = f.f_back
        rv = "(unknown file)", 0, "(unknown function)"
        while hasattr(f, "f_code"):
            co = f.f_code
            filename = os.path.normcase(co.co_filename)
            if filename == _srcfile:
                f = f.f_back
                continue
            rv = (co.co_filename, f.f_lineno, co.co_name)
            break
        return rv
    

    returns the first function in the chain of callers which doesn't belong to the current module.

    You could subclass Logger and override this method by adding a slightly more complex logic. skipping another level of calling depth or adding another condition.


    In your very special case, it would probably be simpler to refrain from the automatic line splitting and to do

    logger.progress('Hello %s', name)
    logger.progress('How are you doing?')
    

    or to do

    def splitter(txt, *args)
        txt = txt % (args)
        for line in txt.split('\n'):
            yield line
    
    for line in splitter('Hello %s\nHow are you doing?', name):
        logger.progress(line)
    

    and have a

    def progress(self, txt, *args):
        self.log(self.PROGRESS, txt, *args)
    

    Probably it will save you a lot of headache.

    EDIT 2: No, that won't help. It now would show you progress as your caller function name...

提交回复
热议问题