-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlogging_lib.py
More file actions
208 lines (157 loc) · 5.12 KB
/
logging_lib.py
File metadata and controls
208 lines (157 loc) · 5.12 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import logging
import time
import json
from typing import Callable
from uuid import uuid4
from fastapi import FastAPI, Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import Message
class RouterLoggingMiddleware(BaseHTTPMiddleware):
def __init__(
self,
app: FastAPI,
*,
logger: logging.Logger
) -> None:
self._logger = logger
super().__init__(app)
async def dispatch(
self,
request: Request,
call_next: Callable
) -> Response:
'''
This method is called for each request.
It logs the request and response part of the request-response cycle.
Arguments:
- request: Request
Returns:
- response: Response
'''
request_id: str = str(uuid4())
logging_dict = {
"X-API-REQUEST-ID": request_id # X-API-REQUEST-ID maps each request-response to a unique ID
}
await self.set_body(request)
response, response_dict = await self._log_response(call_next, request, request_id)
request_dict = await self._log_request(request)
logging_dict["request"] = request_dict
logging_dict["response"] = response_dict
self._logger.info(logging_dict)
return response
async def set_body(self, request: Request):
"""
Avails the response body to be logged within a middleware as, it is generally not a standard practice.
Arguments:
- request: Request
Returns:
- receive_: Receive
"""
receive_ = await request._receive()
async def receive() -> Message:
return receive_
request._receive = receive
async def _log_request(
self,
request: Request
) -> str:
"""
Logs request part
Arguments:
- request: Request
Returns:
- request_logging: str
"""
path = request.url.path
if request.query_params:
path += f"?{request.query_params}"
request_logging = {
"method": request.method,
"path": path,
"ip": request.client.host
}
try:
body = await request.json()
request_logging["body"] = body
except:
body = None
return request_logging
async def _log_response(
self,
call_next: Callable,
request: Request,
request_id: str
) -> Response:
"""
Logs response part
Arguments:
- call_next: Callable (To execute the actual path function and get response back)
- request: Request
- request_id: str (uuid)
Returns:
- response: Response
- response_logging: str
"""
start_time = time.perf_counter()
response = await self._execute_request(call_next, request, request_id)
finish_time = time.perf_counter()
overall_status = "successful" if response.status_code < 400 else "failed"
execution_time = finish_time - start_time
response_logging = {
"status": overall_status,
"status_code": response.status_code,
"time_taken": f"{execution_time:0.4f}s"
}
resp_body = [section async for section in response.__dict__["body_iterator"]]
response.__setattr__("body_iterator", AsyncIteratorWrapper(resp_body))
try:
resp_body = json.loads(resp_body[0].decode())
except:
resp_body = str(resp_body)
response_logging["body"] = resp_body
return response, response_logging
async def _execute_request(
self,
call_next: Callable,
request: Request,
request_id: str
) -> Response:
"""
Executes the actual path function using call_next.
It also injects "X-API-Request-ID" header to the response.
Arguments:
- call_next: Callable (To execute the actual path function
and get response back)
- request: Request
- request_id: str (uuid)
Returns:
- response: Response
"""
try:
response: Response = await call_next(request)
# Kickback X-Request-ID
response.headers["X-API-Request-ID"] = request_id
return response
except Exception as e:
self._logger.exception(
{
"path": request.url.path,
"method": request.method,
"reason": e
}
)
class AsyncIteratorWrapper:
"""
The following is a utility class that transforms a regular iterable to an asynchronous one.
link: https://www.python.org/dev/peps/pep-0492/#example-2
"""
def __init__(self, obj):
self._it = iter(obj)
def __aiter__(self):
return self
async def __anext__(self):
try:
value = next(self._it)
except StopIteration:
raise StopAsyncIteration
return value