This repository has been archived by the owner on Dec 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
middleware.py
65 lines (50 loc) · 1.89 KB
/
middleware.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import json
import re
import time
from flask import current_app, request
IS_PROTOCOL = r'^[^\s]+\:\S'
IS_HOSTNAME = r'^[^\s]+\.\S'
def request_timer():
"""
before_request middleware that attaches the processing start time to the
request object, for later performance assessment.
"""
request.start_time = time.time()
def request_summary(response):
"""
after_request middleware that generates and logs a mozlog-formatted log
about the request.
Read more:
https://github.com/mozilla/universal-search/blob/master/docs/metrics.md
https://github.com/mozilla-services/Dockerflow/blob/master/docs/mozlog.md
"""
request.finish_time = time.time()
response.direct_passthrough = False
log = {
'predicates': {}
}
query = request.args.get('q')
data = response.get_data(as_text=True)
try:
body = json.loads(data)
except json.decoder.JSONDecodeError:
body = {}
log['agent'] = request.headers.get('User-Agent')
log['errno'] = 0 if response.status_code < 400 else response.status_code
log['lang'] = request.headers.get('Accept-Language')
log['method'] = request.method
log['path'] = request.path
log['t'] = request.finish_time - request.start_time
if query:
log['predicates']['query_length'] = len(query) > 20
log['predicates']['is_protocol'] = (re.match(IS_PROTOCOL, query) is not
None)
log['predicates']['is_hostname'] = (re.match(IS_HOSTNAME, query) is not
None)
if not any(log['predicates'].values()):
log['query'] = query if query else None
log['status_code'] = response.status_code
classifiers = body.get('enhancements')
log['classifiers'] = list(classifiers.keys()) if classifiers else []
current_app.logger.info('', extra=log)
return response