|
1
|
|
|
class SentryExceptionHandler: |
|
2
|
|
|
exclude = type(None) |
|
3
|
|
|
|
|
4
|
|
|
def __init__(self, client): |
|
5
|
|
|
self.client = client |
|
6
|
|
|
|
|
7
|
|
|
def __call__(self, request, response, exception): |
|
8
|
|
|
data = { |
|
9
|
|
|
'request': { |
|
10
|
|
|
'url': request.url, |
|
11
|
|
|
'method': request.method, |
|
12
|
|
|
'query_string': request.query_string, |
|
13
|
|
|
'headers': list(request.headers.items()), |
|
14
|
|
|
'cookies': list(request.cookies.items()), |
|
15
|
|
|
'env': self.clean_environment(request.env) |
|
16
|
|
|
}, |
|
17
|
|
|
'user': { |
|
18
|
|
|
# 'id': 'testuser', |
|
19
|
|
|
# 'username': 'fkochem', |
|
20
|
|
|
'ip_address': self.guess_user_ip_from_request(request) |
|
21
|
|
|
# 'email': '[email protected]' |
|
22
|
|
|
} |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
self.client.captureException(data=data) |
|
26
|
|
|
|
|
27
|
|
|
raise exception |
|
28
|
|
|
|
|
29
|
|
|
def clean_environment(self, env): |
|
30
|
|
|
""" |
|
31
|
|
|
Only keep 'REMOTE_ADDR' and environment attributes which begin |
|
32
|
|
|
with 'SERVER_'. |
|
33
|
|
|
""" |
|
34
|
|
|
cleaned_env = {} |
|
35
|
|
|
|
|
36
|
|
|
for key, value in env.items(): |
|
37
|
|
|
if key.startswith('SERVER_') or key == 'REMOTE_ADDR': |
|
38
|
|
|
cleaned_env[key] = value |
|
39
|
|
|
|
|
40
|
|
|
return cleaned_env |
|
41
|
|
|
|
|
42
|
|
|
def guess_user_ip_from_request(self, request): |
|
43
|
|
|
""" |
|
44
|
|
|
Return 'X-FORWARDED-FOR' from the request headers if set, |
|
45
|
|
|
otherwise return 'REMOTE_ADDR' from the environment. If both are |
|
46
|
|
|
not set, return '127.0.0.1'. |
|
47
|
|
|
""" |
|
48
|
|
|
forwarded_for = request.headers.get('X-FORWARDED-FOR', None) |
|
49
|
|
|
if forwarded_for: |
|
50
|
|
|
return forwarded_for |
|
51
|
|
|
|
|
52
|
|
|
remote_addr = request.env.get('REMOTE_ADDR', None) |
|
53
|
|
|
if remote_addr: |
|
54
|
|
|
return remote_addr |
|
55
|
|
|
|
|
56
|
|
|
return '127.0.0.1' |
|
57
|
|
|
|