add operation log

This commit is contained in:
2025-02-01 14:23:43 +09:00
parent 160367f91b
commit b502a3ba8f
5 changed files with 63 additions and 44 deletions

View File

@@ -6,47 +6,57 @@ from app.db.models import OperationLog,User
from functools import wraps
from fastapi import Request
from contextvars import ContextVar
import json
def log_operation(func):
"""自定义装饰器用于记录操作日志"""
@wraps(func)
async def wrapper(*args, **kwargs):
if 'request' in kwargs and isinstance(kwargs['request'], Request):
request: Request = kwargs['request']
method = request.method
url = str(request.url)
client_ip = request.client.host
headers = dict(request.headers)
user_agent = headers.get("user-agent", "")
if 'db' in kwargs and isinstance(kwargs['db'], Session):
db = kwargs['db']
if 'user' in kwargs and isinstance(kwargs['user'], User):
user = kwargs['user']
user_id = user.id
tenant_id = user.tenantid
class LoggingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
if hasattr(request.state, "user") and hasattr(request.state, "tenant"):
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:
user_id = None
tenant_id = None
request.state.body = None
try:
response = await call_next(request)
state = request.state
except Exception as e:
await self.log_error(request, e)
raise
try:
response = await func(*args, **kwargs)
if db:
db_operation = OperationLog(tenantid =tenant_id,
clientip =client_ip,
useragent =user_agent,
userid = user_id,
operation = method,
function = url,
response = f"status_code:{response.status_code }" )
db.add(db_operation)
db.commit()
except Exception as e:
raise e
await self.log_request(request, response,state)
else:
response = await call_next(request)
return response
return wrapper
async def log_request(self, request: Request, response,state):
try:
headers = dict(request.headers)
db_operation = OperationLog(tenantid =request.state.tenant,
clientip = request.client.host if request.client else None,
useragent =headers.get("user-agent", ""),
userid = request.state.user.id,
operation = request.method,
function = request.url.path,
response = f"status_code:{response.status_code }" )
db = request.state.db
if db:
await self.write_log_to_db(db_operation,db)
except Exception as e:
print(f"Logging failed: {str(e)}")
async def log_error(self, request: Request, exc: Exception):
# 错误处理逻辑
pass
async def write_log_to_db(self, db_operation,db):
db.add(db_operation)
db.commit()