Skip to content

Instantly share code, notes, and snippets.

@Ignas
Created May 14, 2012 12:43
Show Gist options
  • Save Ignas/2693732 to your computer and use it in GitHub Desktop.
Save Ignas/2693732 to your computer and use it in GitHub Desktop.
exc_log + Dozer request log handler
from __future__ import absolute_import
import logging
import sys
from dozer.logview import RequestHandler
from pyramid.tweens import EXCVIEW
from pyramid.settings import aslist
from pyramid.util import DottedNameResolver
from pyramid.httpexceptions import WSGIHTTPException
try:
import thread
import threading
except ImportError:
thread = None
resolver = DottedNameResolver(None)
PY3 = sys.version_info[0] == 3
if PY3: # pragma: no cover
import builtins
else:
import __builtin__ as builtins
def as_globals_list(value):
L = []
value = aslist(value)
for dottedname in value:
if dottedname in builtins.__dict__:
if PY3: # pragma: no cover
dottedname = 'builtins.%s' % dottedname
else:
dottedname = '__builtin__.%s' % dottedname
obj = resolver.resolve(dottedname)
L.append(obj)
return L
def exclog_tween_factory(handler, registry):
get = registry.settings.get
ignored = get('exclog.ignore', (WSGIHTTPException,))
reqhandler = RequestHandler()
reqhandler.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(reqhandler)
for logger in logging.getLogger().manager.loggerDict.values():
propagate = getattr(logger, 'propagate', 1)
if propagate == 0:
logger.addHandler(reqhandler)
def exclog_tween(request):
if thread:
tok = thread.get_ident()
else:
tok = None
try:
return handler(request)
except ignored:
raise
except:
reqlogs = reqhandler.pop_events(tok)
logger = logging.getLogger('exc_logger')
for record in reqlogs:
logger.handle(record)
logger.exception(request.url)
raise
finally:
reqhandler.pop_events(tok)
return exclog_tween
def includeme(config):
"""
Set up am implicit :term:`tween` to log exception information that is
generated by your Pyramid application. The logging data will be sent to
the Python logger named ``exc_logger``.
This tween configured to be placed 'below' the exception view tween. It
will log all exceptions (even those eventually caught by a Pyramid
exception view) except 'http exceptions' (any exception that derives from
``pyramid.httpexceptions.WSGIHTTPException`` such as ``HTTPFound``). You
can instruct ``pyramid_exclog`` to ignore custom exception types by using
the ``excview.ignore`` configuration setting.
"""
get = config.registry.settings.get
ignored = as_globals_list(get('exclog.ignore',
'pyramid.httpexceptions.WSGIHTTPException'))
config.registry.settings['exclog.ignore'] = tuple(ignored)
config.add_tween('busy.lib.exc_log2.exclog_tween_factory', under=EXCVIEW)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment