我发现这样做的唯一方法是覆盖 Raven 的一些内部方法。
基本思想是我们要修改Raven 类handle_exception()
上的方法。Sentry
在那里,我可以注入sentry.interfaces.User
问题中已经提到的接口。为此,我需要自己的过滤器工厂,然后我可以使用它来代替 Raven 附带的默认粘贴过滤器,它使用我自己的Sentry
.
在我的项目中,我有一个文件sentry.py
:
from raven.middleware import Sentry
from raven.utils.wsgi import get_current_url, get_headers, get_environ
from raven.base import Client
def sentry_filter_factory(app, global_conf, **kwargs):
""" Overwritten just to override the 'Sentry' class being used. """
client = Client(**kwargs)
return UserEnhancedSentry(app, client)
class UserEnhancedSentry(Sentry):
""" Overriding raven.middleware.Sentry's handle_exception() method to inject
the sentry.interfaces.User interface. This relies on the data previously
being injected into the environ by our custom tween. """
def handle_exception(self, environ):
data={}
data['sentry.interfaces.Http'] = {
'method': environ.get('REQUEST_METHOD'),
'url': get_current_url(environ, strip_querystring=True),
'query_string': environ.get('QUERY_STRING'),
# TODO
# 'data': environ.get('wsgi.input'),
'headers': dict(get_headers(environ)),
'env': dict(get_environ(environ)),
}
if environ.has_key('myapp.user'):
user_id, username, email = environ.get('myapp.user')
ip_address = environ.get('HTTP_X_FORWARDED_FOR', environ.get('REMOTE_ADDR'))
data['sentry.interfaces.User'] = {
'id': user_id,
'username': username,
'email': email,
'ip_address': ip_address,
}
event_id = self.client.captureException(data=data)
return event_id
在我的setup.py
中,我将过滤器工厂声明为入口点:
entry_points = """\
[paste.app_factory]
main = myapp:main
[paste.filter_app_factory]
raven = myapp.sentry:sentry_filter_factory
""",
现在我可以使用入口点在我的配置 .ini 文件中声明一个过滤器并将其集成到粘贴管道中,正如粘贴文档中所述:
[pipeline:main]
pipeline =
sentry
myapp
[filter:sentry]
use = egg:myapp#raven
dsn = https://abc:def@app.getsentry.com/123
所以现在,每当 Sentry 过滤器捕获到异常时,它不仅会存储有关 HTTP 请求的数据,还会存储有关用户的数据——假设它可以在environ
. 我现在要做的就是从那里的会话中注入用户信息,我正在使用自定义补间:
def sentry_user_tween_factory(handler, registry):
""" Returns a tween that does nothing but enhance the environ by information about the currently
logged in user, which will be useful for the Sentry report in case there's an exception """
def sentry_user_tween(request):
user = request.session.get('user')
if user:
request.environ['myapp.user'] = (user.token, user.name, user.email)
else:
request.environ['myapp.user'] = (0, 'anonymous', None)
# proceed with the next tween/handler
response = handler(request)
return response
return sentry_user_tween
config.add_tween('myapp.sentry_user_tween_factory')
这一切看起来都非常复杂,但我很高兴我终于找到了让它工作的方法。