bugfix LoggingMiddleware

This commit is contained in:
2025-02-01 14:47:21 +09:00
parent af959469de
commit 2627c57b30

View File

@@ -11,25 +11,25 @@ import json
class LoggingMiddleware(BaseHTTPMiddleware): class LoggingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next): async def dispatch(self, request: Request, call_next):
if request.method in ("POST", "PUT", "PATCH","DELETE"): if request.method in ("POST", "PUT", "PATCH","DELETE"):
try:
request.state.body = await request.json()
except json.JSONDecodeError:
request.state.body = await request.body()
else:
request.state.body = None
try: try:
response = await call_next(request) request.state.body = await request.json()
state = request.state except json.JSONDecodeError:
except Exception as e: request.state.body = await request.body()
await self.log_error(request, e) else:
raise request.state.body = None
if hasattr(request.state, "user") and hasattr(request.state, "tenant"):
await self.log_request(request, response,state)
return response try:
response = await call_next(request)
state = request.state
except Exception as e:
await self.log_error(request, e)
raise
if hasattr(request.state, "user") and hasattr(request.state, "tenant"):
await self.log_request(request, response,state)
return response
async def log_request(self, request: Request, response,state): async def log_request(self, request: Request, response,state):
try: try: