Tags: #python #tornado #exceptions #handling
"""
Exception is still sent to stdout, so if your service is configured
to send all stdout to a log aggregator you'll get both a load of
log noise followed by a single log call that consolidates it all.
See https://gist.github.com/1140bcd773616ecdae9bb4d2e9e55b34 for a
logging/metrics abstraction (+ tornado implementation) that ties
this write_error function together nicely.
"""
import tornado
import traceback
class CustomHandler(tornado.web.RequestHandler):
def write_error(self, status_code, **kwargs):
if kwargs.get('exc_info'):
# dealing with an unhandled exception
stack_trace = '\n'.join([line for line in traceback.format_exception(*kwargs["exc_info"])])
logger.error('uh-oh', stack=stack_trace)
self.set_status(500)
self.finish()