数据库监控日志、接口监控,熔断机制,提高连接池
This commit is contained in:
60
app/main.py
60
app/main.py
@@ -6,6 +6,7 @@ import logging
|
||||
from .core.config import settings
|
||||
from .core.logging_config import setup_logging, get_logger
|
||||
from .core.database import init_db
|
||||
from .core.db_monitor import start_monitoring, log_pool_status, get_pool_status
|
||||
from .api.account import router as account_router
|
||||
from .api.database import router as database_router
|
||||
from .api.task import router as task_router
|
||||
@@ -34,6 +35,17 @@ async def lifespan(app: FastAPI):
|
||||
except Exception as e:
|
||||
logger.error(f"数据库初始化失败: {e}")
|
||||
|
||||
# 启动数据库监控
|
||||
try:
|
||||
start_monitoring()
|
||||
logger.info("数据库连接池监控已启动")
|
||||
|
||||
# 记录初始连接池状态
|
||||
pool_stats = get_pool_status()
|
||||
logger.info(f"初始连接池状态: {pool_stats}")
|
||||
except Exception as e:
|
||||
logger.error(f"数据库监控启动失败: {e}")
|
||||
|
||||
# 启动定时任务调度器
|
||||
try:
|
||||
task_scheduler.start()
|
||||
@@ -45,6 +57,14 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
# 关闭时执行
|
||||
logger.info("应用关闭中...")
|
||||
|
||||
# 记录最终连接池状态
|
||||
try:
|
||||
pool_stats = get_pool_status()
|
||||
logger.info(f"最终连接池状态: {pool_stats}")
|
||||
except Exception as e:
|
||||
logger.error(f"获取最终连接池状态失败: {e}")
|
||||
|
||||
try:
|
||||
task_scheduler.shutdown()
|
||||
logger.info("定时任务调度器已关闭")
|
||||
@@ -101,11 +121,47 @@ async def health_check():
|
||||
"scheduler": "running" if task_scheduler.scheduler.running else "stopped"
|
||||
}
|
||||
|
||||
# 数据库监控端点
|
||||
@app.get("/api/monitor/database")
|
||||
async def get_database_monitor():
|
||||
"""获取数据库连接池监控信息"""
|
||||
from .core.db_monitor import get_monitoring_report
|
||||
return get_monitoring_report()
|
||||
|
||||
# 连接池状态端点
|
||||
@app.get("/api/monitor/pool")
|
||||
async def get_pool_status():
|
||||
"""获取连接池状态"""
|
||||
from .core.db_monitor import get_pool_status
|
||||
return get_pool_status()
|
||||
|
||||
# 全局异常处理
|
||||
@app.exception_handler(Exception)
|
||||
async def global_exception_handler(request, exc):
|
||||
logger.error(f"全局异常: {str(exc)}")
|
||||
"""全局异常处理"""
|
||||
import traceback
|
||||
from .core.db_monitor import get_pool_status
|
||||
|
||||
# 获取异常详情
|
||||
error_msg = str(exc)
|
||||
error_type = type(exc).__name__
|
||||
stack_trace = traceback.format_exc()
|
||||
|
||||
# 获取当前连接池状态
|
||||
try:
|
||||
pool_stats = get_pool_status()
|
||||
pool_info = f", 连接池使用率: {pool_stats.get('usage_percent', 'N/A')}%"
|
||||
except:
|
||||
pool_info = ""
|
||||
|
||||
# 记录详细错误日志
|
||||
logger.error(
|
||||
f"🚨 全局异常: {error_type}: {error_msg} "
|
||||
f"请求路径: {request.url.path}, 方法: {request.method}{pool_info}\n"
|
||||
f"堆栈跟踪:\n{stack_trace}"
|
||||
)
|
||||
|
||||
return HTTPException(
|
||||
status_code=500,
|
||||
detail="服务器内部错误"
|
||||
detail=f"服务器内部错误: {error_type}"
|
||||
)
|
||||
Reference in New Issue
Block a user