You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
1023 B
33 lines
1023 B
1 month ago
|
from functools import wraps
|
||
|
from fastapi import Request
|
||
|
from app.core.logger import logger
|
||
|
import time
|
||
|
|
||
|
class RequestLogger:
|
||
|
"""请求日志中间件"""
|
||
|
|
||
|
@staticmethod
|
||
|
def log_request(f):
|
||
|
@wraps(f)
|
||
|
async def decorated_function(request: Request, *args, **kwargs):
|
||
|
start_time = time.time()
|
||
|
|
||
|
# 记录请求信息
|
||
|
logger.info(f"收到请求 - 方法: {request.method}, 路径: {request.url.path}")
|
||
|
|
||
|
# 尝试获取请求体
|
||
|
try:
|
||
|
body = await request.json()
|
||
|
logger.debug(f"请求体: {body}")
|
||
|
except:
|
||
|
pass
|
||
|
|
||
|
# 执行请求处理
|
||
|
response = await f(request, *args, **kwargs)
|
||
|
|
||
|
# 记录响应时间
|
||
|
duration = time.time() - start_time
|
||
|
logger.info(f"请求处理完成 - 耗时: {duration:.2f}秒")
|
||
|
|
||
|
return response
|
||
|
return decorated_function
|