refactor(logging): introduce centralized logging and FastAPI lifespan
Some checks failed
Build and Push Docker / build-and-push (push) Failing after 2m38s
Some checks failed
Build and Push Docker / build-and-push (push) Failing after 2m38s
This commit is contained in:
@ -4,6 +4,7 @@ import threading
|
||||
from datetime import datetime
|
||||
import sys
|
||||
import os
|
||||
import logging
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from config import (
|
||||
@ -13,6 +14,8 @@ from config import (
|
||||
from api.doubao_tts import text_to_speech
|
||||
from memory_module.memory_integration import Mem0Integration
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ChatService:
|
||||
def __init__(self, user_id: str = None):
|
||||
@ -25,7 +28,7 @@ class ChatService:
|
||||
if self._initialized:
|
||||
return
|
||||
|
||||
print(f"[INFO] Initializing Mem0 integration for user: {self.user_id}")
|
||||
logger.info(f"Initializing Mem0 integration for user: {self.user_id}")
|
||||
self._initialized = True
|
||||
|
||||
def chat(self, user_input: str, include_audio: bool = True) -> Dict[str, Any]:
|
||||
|
47
api/main.py
47
api/main.py
@ -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
|
||||
)
|
||||
)
|
||||
|
Reference in New Issue
Block a user