update operation

This commit is contained in:
2025-02-01 19:40:01 +09:00
parent f27c0728b7
commit f70a2cfde6
2 changed files with 16 additions and 10 deletions

View File

@@ -15,7 +15,6 @@ def get_db(request: Request,tenant:str = "1",tenantdb = Depends(get_tenant_db)):
db.close() db.close()
def get_log_db(request: Request): def get_log_db():
db = tenantdb.get_db() db = tenantdb.get_db()
request.state.db = db
return db return db

View File

@@ -1,12 +1,12 @@
from fastapi import Request from fastapi import Request
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.base import BaseHTTPMiddleware
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.db.models import OperationLog,User from app.db.models import OperationLog,User
from app.core.apiexception import APIException
from functools import wraps from app.core.dbmanager import get_log_db
from fastapi import Request from app.db.crud import create_log
from contextvars import ContextVar
import json import json
class LoggingMiddleware(BaseHTTPMiddleware): class LoggingMiddleware(BaseHTTPMiddleware):
@@ -24,7 +24,10 @@ class LoggingMiddleware(BaseHTTPMiddleware):
state = request.state state = request.state
except Exception as e: except Exception as e:
await self.log_error(request, e) await self.log_error(request, e)
raise response = JSONResponse(
content={"detail": "Internal Server Error"},
status_code=500
)
if hasattr(request.state, "user") and hasattr(request.state, "tenant"): if hasattr(request.state, "user") and hasattr(request.state, "tenant"):
await self.log_request(request, response,state) await self.log_request(request, response,state)
@@ -51,9 +54,13 @@ class LoggingMiddleware(BaseHTTPMiddleware):
print(f"Logging failed: {str(e)}") print(f"Logging failed: {str(e)}")
async def log_error(self, request: Request, exc: Exception): async def log_error(self, request: Request, e: Exception):
# 错误处理逻辑 exc = APIException('operation:dispatch',request.url._url,f"Error occurred while writting operation log:",e)
pass db = get_log_db()
try:
create_log(db,exc.error)
finally:
db.close()
async def write_log_to_db(self, db_operation,db): async def write_log_to_db(self, db_operation,db):
db.add(db_operation) db.add(db_operation)