How to log source file name and line number in Python

后端 未结 5 1066
北海茫月
北海茫月 2020-11-29 16:52

Is it possible to decorate/extend the python standard logging system, so that when a logging method is invoked it also logs the file and the line number where it was invoked

5条回答
  •  孤街浪徒
    2020-11-29 17:02

    # your imports above ...
    
    
    logging.basicConfig(
        format='%(asctime)s,%(msecs)d %(levelname)-8s [%(pathname)s:%(lineno)d in 
        function %(funcName)s] %(message)s',
        datefmt='%Y-%m-%d:%H:%M:%S',
        level=logging.DEBUG
    )
    
    logger = logging.getLogger(__name__)
    
    # your classes and methods below ...
    # An naive Sample of usage:
    try:
        logger.info('Sample of info log')
        # your code here
    except Exception as e:
        logger.error(e)
    

    Different of the other answers, this will log full path of file and the function name that might have occurred an error. This is useful if you have a project with more than one module and several files with the same name distributed in these modules.

提交回复
热议问题