Skip to content

Instantly share code, notes, and snippets.

@brickZA
Last active August 29, 2015 14:08
Show Gist options
  • Save brickZA/0197f428ff2bb207c2a1 to your computer and use it in GitHub Desktop.
Save brickZA/0197f428ff2bb207c2a1 to your computer and use it in GitHub Desktop.
Logging a future exception
import tornado
from functools import wraps
def log_coroutine_exceptions(coro):
"""Coroutine (or any method that returns a future) decorator to log exceptions
Example
-------
::
@log_coroutine_exceptions
@tornado.gen.coroutine
def raiser(self, arg):
yield tornado.gen.moment
raise Exception(arg)
Assuming that your object (self) has a `log` attribute containing a logger instance
"""
def log_cb(self, f):
try:
f.result()
except Exception:
self.log.exception('Unhandled exception calling coroutine {0!r}'
.format(coro))
@wraps(coro)
def wrapped_coro(self, *args, **kwargs):
f = coro(self, *args, **kwargs)
f.add_done_callback(partial(log_cb, self))
return f
return wrapped_coro
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment