How to log source file name and line number in Python

后端 未结 5 1039
北海茫月
北海茫月 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:24

    To build on the above in a way that sends debug logging to standard out:

    import logging
    import sys
    
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.DEBUG)
    FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
    formatter = logging.Formatter(FORMAT)
    ch.setFormatter(formatter)
    root.addHandler(ch)
    
    logging.debug("I am sent to standard out.")
    

    Putting the above into a file called debug_logging_example.py produces the output:

    [debug_logging_example.py:14 -             () ] I am sent to standard out.
    

    Then if you want to turn off logging comment out root.setLevel(logging.DEBUG).

    For single files (e.g. class assignments) I've found this a far better way of doing this as opposed to using print() statements. Where it allows you to turn the debug output off in a single place before you submit it.

提交回复
热议问题