Skip to content

Commit 87df845

Browse files
committed
refactor: little LoggindMiddleware changes to save few processor ticks
1 parent fbef950 commit 87df845

File tree

2 files changed

+22
-12
lines changed

2 files changed

+22
-12
lines changed

microbootstrap/middlewares/fastapi.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,19 +21,22 @@ async def dispatch(
2121
should_log: typing.Final = not any(
2222
exclude_endpoint == request_path for exclude_endpoint in exclude_endpoints
2323
)
24+
25+
if not should_log:
26+
return await call_next(request)
27+
2428
start_time: typing.Final = time.perf_counter_ns()
2529
try:
2630
response = await call_next(request)
2731
except Exception: # noqa: BLE001
2832
response = fastapi.Response(status_code=500)
2933

30-
if should_log:
31-
fill_log_message(
32-
"exception" if response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR else "info",
33-
request,
34-
response.status_code,
35-
start_time,
36-
)
34+
fill_log_message(
35+
"exception" if response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR else "info",
36+
request,
37+
response.status_code,
38+
start_time,
39+
)
3740
return response
3841

3942
return FastAPILoggingMiddleware

microbootstrap/middlewares/litestar.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,21 @@ async def __call__(
2424
send_function: litestar.types.Send,
2525
) -> None:
2626
request: typing.Final[litestar.Request] = litestar.Request(request_scope) # type: ignore[type-arg]
27+
28+
request_path = request.url.path.removesuffix("/")
29+
should_log: typing.Final = not any(one_endpoint == request_path for one_endpoint in exclude_endpoints)
30+
31+
if not should_log:
32+
await self.app(request_scope, receive, send_function)
33+
return
34+
2735
start_time: typing.Final[int] = time.perf_counter_ns()
2836

2937
async def log_message_wrapper(message: litestar.types.Message) -> None:
30-
request_path = request.url.path.removesuffix("/")
31-
should_log: typing.Final = not any(one_endpoint == request_path for one_endpoint in exclude_endpoints)
32-
if message["type"] == "http.response.start" and should_log:
33-
log_level: str = "info" if message["status"] < HTTP_500_INTERNAL_SERVER_ERROR else "exception"
34-
fill_log_message(log_level, request, message["status"], start_time)
38+
if message["type"] == "http.response.start":
39+
status = message["status"]
40+
log_level: str = "info" if status < HTTP_500_INTERNAL_SERVER_ERROR else "exception"
41+
fill_log_message(log_level, request, status, start_time)
3542

3643
await send_function(message)
3744

0 commit comments

Comments
 (0)