0

By default, Python Bottle with WSGIRefServer logs the uncaught exceptions to stderr (and stdout for requests logging).

I'd like to log uncaught exceptions to a logging logger object. The following code with monkey-patching seems to work, but what is the standard way to do it following the official WSGI specification?

import logging, sys

logging.basicConfig(filename='test4.log', filemode='a', format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)
log = logging.getLogger('foobar')
log.info("hello")

class LoggerWriter:
    def __init__(self, level):
        self.level = level
    def write(self, message):
        self.level(message.strip())
    def flush(self):
        pass

sys.stdout = LoggerWriter(log.info)
sys.stderr = LoggerWriter(log.error)
from bottle import route, run, template, request
@route('/')
def index():
    sqdf         # uncaught exception !!! 
    return "hhello"
run()

Notes:

  • see How to redirect stdout and stderr to logger in Python

  • the WSGI standard requires that logging is done through a file-like object wsgi.errors, how to redirect this to a logging logger?

  • this attempt does not work:

    import logging, sys, traceback
    logging.basicConfig(filename='test.log', filemode='a', format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)
    sys.excepthook = lambda exctype, value, tb: logging.error("", exc_info=(exctype, value, tb))
    logging.info("hello")
    from bottle import route, run, template, request
    @route('/')
    def index():
        sqdf         # uncaught exception !!! not logged 
        return "hello"
    run()
    
Basj
  • 41,386
  • 99
  • 383
  • 673

0 Answers0