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

1from datetime import UTC, datetime 

2 

3# from app.core.exception import DomainException, UseCaseException 

4from logging import getLogger 

5 

6from fastapi import Request, Response 

7from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint 

8 

9# handler_format = Formatter('%(levelname)s: %(asctime)s - %(name)s - %(message)s') 

10 

11# stream_handler = StreamHandler() 

12# stream_handler.setFormatter(handler_format) 

13 

14logger = getLogger("main").getChild("logging_middleware") 

15# logger.setLevel(DEBUG) 

16# logger.addHandler(stream_handler) 

17 

18 

19 

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") 

24 

25 response: Response = await call_next(request) 

26 

27 

28 # error handling 後を含めた実行について保存する 

29 

30 end_datetime = datetime.now(UTC) 

31 duration = end_datetime - start_datetime 

32 

33 # ヘッダに情報をトレインケースで埋める 

34 # 後で分けると思う 

35 response.headers["X-Resource-Code"] = "RRR" 

36 response.headers["X-Action-Code"] = "A" 

37 response.headers["X-Error-Code"] = "EEE" 

38 

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"] 

41 

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) 

46 

47 

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}") 

55 

56 return response