Coverage for app/core/middleware/logging_middleware.py: 100%
26 statements
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-15 01:44 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-15 01:44 +0000
1from datetime import UTC, datetime
3# from app.core.exception import DomainException, UseCaseException
4from logging import getLogger
6from fastapi import Request, Response
7from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
9# handler_format = Formatter('%(levelname)s: %(asctime)s - %(name)s - %(message)s')
11# stream_handler = StreamHandler()
12# stream_handler.setFormatter(handler_format)
14logger = getLogger("main").getChild("logging_middleware")
15# logger.setLevel(DEBUG)
16# logger.addHandler(stream_handler)
20class LoggingMiddleware(BaseHTTPMiddleware):
21 async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
22 start_datetime = datetime.now(UTC)
23 print("logging middleware : api start")
25 response: Response = await call_next(request)
28 # error handling 後を含めた実行について保存する
30 end_datetime = datetime.now(UTC)
31 duration = end_datetime - start_datetime
33 # ヘッダに情報をトレインケースで埋める
34 # 後で分けると思う
35 response.headers["X-Resource-Code"] = "RRR"
36 response.headers["X-Action-Code"] = "A"
37 response.headers["X-Error-Code"] = "EEE"
39 # exception_handling_middlewareでX-Error-Codeは設定する
40 response.headers["X-Result-Code"] = "S" + response.headers["X-Resource-Code"] + response.headers["X-Action-Code"] + response.headers["X-Error-Code"]
42 # 時間に関する記載
43 response.headers["X-Response-Start-Datetime"] = str(start_datetime)
44 response.headers["X-Response-End-Datetime"] = str(end_datetime)
45 response.headers["X-Response-Time"] = str(duration)
48 # レスポンスについてのシステムログを残す
49 logger.info("info")
50 logger.warning("warn")
51 logger.debug("debug")
52 print(request.url)
53 print(response.status_code)
54 print(f"route response headers: {response.headers}")
56 return response