Skip to content

Commit c2e8f3b

Browse files
authored
Merge pull request #19 from bybatkhuu/develop
✨ Added flag for enable/disable HTTP debug log in .
2 parents 2abc3f9 + 72bb40a commit c2e8f3b

File tree

2 files changed

+37
-8
lines changed

2 files changed

+37
-8
lines changed

beans_logging/fastapi/_formats.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,20 @@ def http_file_format(record: dict) -> str:
2020
_http_info = record["extra"]["http_info"]
2121
if "datetime" not in _http_info:
2222
_http_info["datetime"] = record["time"].isoformat()
23-
record["extra"]["http_info"] = _http_info
23+
24+
if "content_length" not in _http_info:
25+
_http_info["content_length"] = 0
26+
27+
if "h_referer" not in _http_info:
28+
_http_info["h_referer"] = "-"
29+
30+
if "h_user_agent" not in _http_info:
31+
_http_info["h_user_agent"] = "-"
32+
33+
if "response_time" not in _http_info:
34+
_http_info["response_time"] = 0
35+
36+
record["extra"]["http_info"] = _http_info
2437

2538
_msg = _MSG_FORMAT.format(**_http_info)
2639
record["http_message"] = _msg

beans_logging/fastapi/_middlewares.py

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ class HttpAccessLogMiddleware(BaseHTTPMiddleware):
2525
has_cf_headers (bool): If True, use cloudflare headers to get http request info. Defaults to False.
2626
debug_format (str ): Http access log debug message format. Defaults to `HttpAccessLogMiddleware._DEBUG_FORMAT`.
2727
msg_format (str ): Http access log message format. Defaults to `HttpAccessLogMiddleware._MSG_FORMAT`.
28+
use_debug_log (bool): If True, use debug log to log http access log. Defaults to True.
2829
"""
2930

3031
_DEBUG_FORMAT = '<n>[{request_id}]</n> {client_host} {user_id} "<u>{method} {url_path}</u> HTTP/{http_version}"'
@@ -37,12 +38,14 @@ def __init__(
3738
has_cf_headers: bool = False,
3839
debug_format: str = _DEBUG_FORMAT,
3940
msg_format: str = _MSG_FORMAT,
41+
use_debug_log: bool = True,
4042
):
4143
super().__init__(app)
4244
self.has_proxy_headers = has_proxy_headers
4345
self.has_cf_headers = has_cf_headers
4446
self.debug_format = debug_format
4547
self.msg_format = msg_format
48+
self.use_debug_log = use_debug_log
4649

4750
async def dispatch(self, request: Request, call_next) -> Response:
4851
_logger = logger.opt(colors=True, record=True)
@@ -53,6 +56,8 @@ async def dispatch(self, request: Request, call_next) -> Response:
5356
_http_info["request_id"] = request.headers.get("X-Request-ID")
5457
elif "X-Correlation-ID" in request.headers:
5558
_http_info["request_id"] = request.headers.get("X-Correlation-ID")
59+
60+
## Set request_id to request state:
5661
request.state.request_id = _http_info["request_id"]
5762

5863
_http_info["client_host"] = request.client.host
@@ -161,16 +166,25 @@ async def dispatch(self, request: Request, call_next) -> Response:
161166
if hasattr(request.state, "user_id"):
162167
_http_info["user_id"] = str(request.state.user_id)
163168

164-
_debug_msg = self.debug_format.format(**_http_info)
165-
# _logger.debug(_debug_msg)
166-
await run_in_threadpool(
167-
_logger.debug,
168-
_debug_msg,
169-
)
169+
## Debug log:
170+
if self.use_debug_log:
171+
_debug_msg = self.debug_format.format(**_http_info)
172+
# _logger.debug(_debug_msg)
173+
await run_in_threadpool(
174+
_logger.debug,
175+
_debug_msg,
176+
)
177+
## Debug log
178+
179+
## Set http info to request state:
180+
request.state.http_info = _http_info
170181

182+
## Process request:
171183
_start_time = time.time()
172184
response = await call_next(request)
173185
_http_info["response_time"] = round((time.time() - _start_time) * 1000, 1)
186+
## Response processed
187+
174188
if "X-Process-Time" in response.headers:
175189
try:
176190
_http_info["response_time"] = float(
@@ -208,6 +222,7 @@ async def dispatch(self, request: Request, call_next) -> Response:
208222
"Can not serialize `http_info` to json string in HttpAccessLogMiddleware!"
209223
)
210224

225+
## Http access log:
211226
_LEVEL = "INFO"
212227
_msg_format = self.msg_format
213228
if _http_info["status_code"] < 200:
@@ -225,7 +240,7 @@ async def dispatch(self, request: Request, call_next) -> Response:
225240
elif 500 <= _http_info["status_code"]:
226241
_LEVEL = "ERROR"
227242
_msg_format = (
228-
f'<r>{_msg_format.replace("{status_code}", "<n>{status_code}</n>")}</r>'
243+
f'{_msg_format.replace("{status_code}", "<n>{status_code}</n>")}'
229244
)
230245

231246
_msg = _msg_format.format(**_http_info)
@@ -235,5 +250,6 @@ async def dispatch(self, request: Request, call_next) -> Response:
235250
_LEVEL,
236251
_msg,
237252
)
253+
## Http access log
238254

239255
return response

0 commit comments

Comments
 (0)