refactor(logging): introduce centralized logging and FastAPI lifespan
Some checks failed
Build and Push Docker / build-and-push (push) Failing after 2m38s

This commit is contained in:
gameloader
2025-10-13 10:17:19 +08:00
parent 0e5199d3c0
commit f1a48874d0
5 changed files with 175 additions and 24 deletions

View File

@ -1,9 +1,25 @@
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
import uvicorn
import os
import sys
# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from chat_service import ChatService
from logging_config import setup_logging, get_logger
# 设置日志
setup_logging(
level=os.getenv('LOG_LEVEL', 'INFO'),
enable_file_logging=os.getenv('ENABLE_FILE_LOGGING', 'false').lower() == 'true'
)
# 获取logger
logger = get_logger(__name__)
# 请求和响应模型
@ -23,21 +39,30 @@ class ChatResponse(BaseModel):
audio_error: Optional[str] = None
# 创建 FastAPI 应用
app = FastAPI(
title="Mem0 Memory API",
description="基于 Mem0 的记忆增强聊天服务 API",
version="1.0.0"
)
# 全局聊天服务实例
chat_service = ChatService()
@app.on_event("startup")
async def startup_event():
"""应用启动时初始化聊天服务"""
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期管理器"""
logger.info("Starting Mem0 Memory API...")
# 应用启动时初始化聊天服务
chat_service.initialize()
logger.info("Mem0 Memory API started successfully")
yield
# 应用关闭时可以在这里执行清理操作
# 例如关闭数据库连接、释放资源等
logger.info("Shutting down Mem0 Memory API...")
# 创建 FastAPI 应用
app = FastAPI(
title="Mem0 Memory API",
description="基于 Mem0 的记忆增强聊天服务 API",
version="1.0.0",
lifespan=lifespan
)
@app.get("/")
@ -80,4 +105,4 @@ if __name__ == "__main__":
host="0.0.0.0",
port=8000,
reload=True
)
)