diff --git a/src/logging/logger.py b/src/logging/logger.py index 4af530c..c270942 100644 --- a/src/logging/logger.py +++ b/src/logging/logger.py @@ -6,6 +6,7 @@ from typing import cast import aiofiles from fastapi import Request +from fastapi.responses import JSONResponse from starlette.concurrency import iterate_in_threadpool from starlette.middleware.base import BaseHTTPMiddleware from starlette.responses import Response, StreamingResponse @@ -23,32 +24,32 @@ class ProcessingTimeMiddleware(BaseHTTPMiddleware): class LoggingMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next) -> Response: current_time = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) - file_time=strftime("%b_%Y", gmtime()) - response = await call_next(request) + file_time = strftime("%b_%Y", gmtime()) + client_ip = request.headers.get('x-forwarded-for', '').split(',')[0].strip() or (request.client.host if request.client else 'unknown') + + try: + response = await call_next(request) + except Exception as exc: # noqa: BLE001 + body = str(exc) + async with aiofiles.open(f"./logs/endpoints_log_{file_time}.txt", "a") as file: + await file.write(f"[{current_time}] [500] [{body}] [{client_ip}]\n") + return JSONResponse(status_code=500, content={"detail": "Internal Server Error"}) + streaming_response = cast(StreamingResponse, response) - + chunks = [] async for chunk in streaming_response.body_iterator: - if isinstance(chunk, str): - chunks.append(chunk.encode()) - else: - chunks.append(bytes(chunk)) + chunks.append(chunk.encode() if isinstance(chunk, str) else bytes(chunk)) body_bytes = b"".join(chunks) streaming_response.body_iterator = iterate_in_threadpool(iter([body_bytes])) try: - body = json.loads(body_bytes) - if not isinstance(body, bool): - body=body.get("detail", None) - else: - body=None - + parsed = json.loads(body_bytes) + body = parsed.get("detail", None) if not isinstance(parsed, bool) else None except (json.JSONDecodeError, TypeError): body = None - client_ip = request.headers.get('x-forwarded-for', '').split(',')[0].strip() or (request.client.host if request.client else 'unknown') - async with aiofiles.open(f"./logs/endpoints_log_{file_time}.txt", "a") as file: await file.write(f"[{current_time}] [{response.status_code}] [{body}] [{client_ip}]\n")