import logging import os import sys import traceback def log_outer(msg, *args): log_inner(msg, *args) def log_inner(msg, *args): logging.info(msg, *args) def patch_logging(): # The directory containing the logging package, as seen by the import machinery. _logging_path = logging.__path__[0] def _handleError(self, record): """ Handle errors which occur during a Handler.emit() call. This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method. """ if logging.raiseExceptions and sys.stderr: # see issue 13807 t, v, tb = sys.exc_info() try: sys.stderr.write('--- Logging error ---\n') traceback.print_exception(t, v, tb, None, sys.stderr) sys.stderr.write('Call stack:\n') # Walk the stack frame up until we're out of logging, # so as to print the calling context. frame = tb.tb_frame while (frame and os.path.dirname(frame.f_code.co_filename) == _logging_path): frame = frame.f_back traceback.print_stack(frame, file=sys.stderr) except IOError: pass # see issue 5971 finally: del t, v, tb logging.Handler.handleError = _handleError if __name__ == "__main__": logging.basicConfig(stream=sys.stderr, level=logging.INFO) log_outer("1: here is %(variable)f", dict(variable=None)) patch_logging() log_outer("2: here is %(variable)s", dict(variables=5))