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
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.