Python Logging (function name, file name, line number) using a single file

后端 未结 3 1943
日久生厌
日久生厌 2020-12-04 05:04

I am trying to learn how an application works. And for this I am inserting debug commands as the first line of each function\'s body with the goal of logging the function\'s

3条回答
  •  爱一瞬间的悲伤
    2020-12-04 05:41

    The correct answer for this is to use the already provided funcName variable

    import logging
    logger = logging.getLogger('root')
    FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
    logging.basicConfig(format=FORMAT)
    logger.setLevel(logging.DEBUG)
    

    Then anywhere you want, just add:

    logger.debug('your message') 
    

    Example output from a script I'm working on right now:

    [invRegex.py:150 -          handleRange() ] ['[A-Z]']
    [invRegex.py:155 -     handleRepetition() ] [[<__main__.CharacterRangeEmitter object at 0x10ba03050>, '{', '1', '}']]
    [invRegex.py:197 -          handleMacro() ] ['\\d']
    [invRegex.py:155 -     handleRepetition() ] [[<__main__.CharacterRangeEmitter object at 0x10ba03950>, '{', '1', '}']]
    [invRegex.py:210 -       handleSequence() ] [[<__main__.GroupEmitter object at 0x10b9fedd0>, <__main__.GroupEmitter object at 0x10ba03ad0>]]
    

提交回复
热议问题