-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathcustom_log_format_request.py
79 lines (58 loc) · 2.45 KB
/
custom_log_format_request.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import json
import logging
import sys
import flask
import json_logging
import json_logging.dto
import json_logging.formatters
class CustomRequestJSONLog(json_logging.formatters.JSONRequestLogFormatter):
"""
Customized logger
"""
def _format_log_object(self, record, request_util):
# request and response object can be extracted from record like this
request = record.request_response_data._request
response = record.request_response_data._response
json_log_object = super(CustomRequestJSONLog, self)._format_log_object(record, request_util)
json_log_object.update({
"customized_prop": "customized value",
})
return json_log_object
class CustomDefaultRequestResponseDTO(json_logging.dto.DefaultRequestResponseDTO):
"""
custom implementation
"""
def __init__(self, request, **kwargs):
super(CustomDefaultRequestResponseDTO, self).__init__(request, **kwargs)
def on_request_complete(self, response):
super(CustomDefaultRequestResponseDTO, self).on_request_complete(response)
self.status = response.status
app = flask.Flask(__name__)
json_logging.init_flask(enable_json=True)
json_logging.init_request_instrument(app, exclude_url_patterns=[r'/exclude_from_request_instrumentation'],
custom_formatter=CustomRequestJSONLog,
request_response_dto_class=CustomDefaultRequestResponseDTO)
# init the logger as usual
logger = logging.getLogger("test logger")
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(sys.stdout))
@app.route('/')
def home():
logger.info("test log statement")
logger.info("test log statement with extra props", extra={'props': {"extra_property": 'extra_value'}})
correlation_id = json_logging.get_correlation_id()
return "hello world" \
"\ncorrelation_id : " + correlation_id
@app.route('/exception')
def exception():
try:
raise RuntimeError
except BaseException as e:
logger.error("Error occurred", exc_info=e)
logger.exception("Error occurred", exc_info=e)
return "Error occurred, check log for detail"
@app.route('/exclude_from_request_instrumentation')
def exclude_from_request_instrumentation():
return "this request wont log request instrumentation information"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=int(5000), use_reloader=False)