Last active
August 29, 2015 14:08
-
-
Save brickZA/0197f428ff2bb207c2a1 to your computer and use it in GitHub Desktop.
Logging a future exception
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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