Skip to content

Instantly share code, notes, and snippets.

@akhenakh
Created September 4, 2012 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save akhenakh/3619525 to your computer and use it in GitHub Desktop.
Save akhenakh/3619525 to your computer and use it in GitHub Desktop.
Flask method view logging handler decorator
import traceback
import datetime
import socket
import os
import resource
...
def log_exception(view_func):
""" log exception decorator for a view,
"""
def _decorator(self, *args, **kwargs):
try:
response = view_func(self, *args, **kwargs)
except:
tb = traceback.format_exc()
# get the view name from request
log_dict = { 'class_method':"%s.%s.%s()" % (self.__class__.__module__, self.__class__.__name__,view_func.func_name),
'method':request.method,
'url':request.url,
'remote':request.remote_addr,
'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])
}
if getattr(g, 'current_user', None):
log_dict['user'] = g.current_user
if len(request.form) > 0:
form = ""
for key in request.form.keys():
form += '%s=\"%s\"\n' % (key,request.form[key])
log_dict['form'] = form
try:
res = mongo.db.log.save(log_dict)
except PyMongoError:
print log_dict
raise
return response
return wraps(view_func)(_decorator)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment