Last active
April 21, 2016 16:12
-
-
Save akhenakh/5825280 to your computer and use it in GitHub Desktop.
Decorator for Tornado function, that will log all exception in MongodB, implies all handlers have a self.db properties connected to mongo
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
def log_exception(view_func): | |
""" log exception decorator for a view, | |
""" | |
def _decorator(self, *args, **kwargs): | |
try: | |
response = view_func(self, *args, **kwargs) | |
except: | |
if self.settings['debug']: | |
raise | |
tb = traceback.format_exc() | |
# get the view name from request | |
log_dict = { 'class_method':"%s.%s" % (self.__class__.__module__, self.__class__.__name__), | |
'method':self.request.method, | |
'url':self.request.full_url(), | |
'remote':self.request.remote_ip, | |
'tb':tb, | |
'date':datetime.datetime.utcnow(), | |
'tb_short':tb.splitlines()[-1], | |
'hostname':socket.gethostname(), | |
'pid':int(os.getpid()), | |
'rss':int(resource.getrusage(resource.RUSAGE_SELF)[2]) | |
} | |
print(log_dict) | |
if getattr(self, 'current_user', None): | |
log_dict['user'] = g.current_user | |
if len(self.request.arguments) > 0: | |
form = "" | |
for key in self.request.arguments.keys(): | |
form += '%s=\"%s\"\n' % (key,self.request.arguments[key]) | |
log_dict['form'] = form | |
try: | |
res = self.db.log.save(log_dict) | |
except PyMongoError: | |
print (log_dict) | |
raise | |
return response | |
return functools.wraps(view_func)(_decorator) | |
class IndexHandler(BaseHandler): | |
@log_exception | |
def get(self): | |
raise IOError | |
self.write("Hello, world") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment