feat: 新增运行时重载配置文件;新增根据不同环境(dev;prod)显示不同级别的log
This commit is contained in:
12
bot.py
12
bot.py
@@ -59,7 +59,7 @@ def init_env():
|
||||
# 检测.env.dev文件是否存在,不存在的话直接复制生产环境配置
|
||||
if not os.path.exists(".env.dev"):
|
||||
logger.error("检测到.env.dev文件不存在")
|
||||
shutil.copy("template.env", "./.env.dev")
|
||||
shutil.copy(".env.prod", "./.env.dev")
|
||||
|
||||
# 首先加载基础环境变量.env
|
||||
if os.path.exists(".env"):
|
||||
@@ -99,6 +99,16 @@ def load_env():
|
||||
|
||||
def load_logger():
|
||||
logger.remove() # 移除默认配置
|
||||
if os.getenv("ENVIRONMENT") == "dev":
|
||||
logger.add(
|
||||
sys.stderr,
|
||||
format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> <fg #777777>|</> <level>{level: <7}</level> <fg "
|
||||
"#777777>|</> <cyan>{name:.<8}</cyan>:<cyan>{function:.<8}</cyan>:<cyan>{line: >4}</cyan> <fg "
|
||||
"#777777>-</> <level>{message}</level>",
|
||||
colorize=True,
|
||||
level=os.getenv("LOG_LEVEL", "DEBUG"), # 根据环境设置日志级别,默认为DEBUG
|
||||
)
|
||||
else:
|
||||
logger.add(
|
||||
sys.stderr,
|
||||
format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> <fg #777777>|</> <level>{level: <7}</level> <fg "
|
||||
|
||||
10
src/plugins/config_reload/__init__.py
Normal file
10
src/plugins/config_reload/__init__.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from nonebot import get_app
|
||||
from .api import router
|
||||
from loguru import logger
|
||||
|
||||
# 获取主应用实例并挂载路由
|
||||
app = get_app()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
# 打印日志,方便确认API已注册
|
||||
logger.success("配置重载API已注册,可通过 /api/reload-config 访问")
|
||||
17
src/plugins/config_reload/api.py
Normal file
17
src/plugins/config_reload/api.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from src.plugins.chat.config import BotConfig
|
||||
import os
|
||||
|
||||
# 创建APIRouter而不是FastAPI实例
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/reload-config")
|
||||
async def reload_config():
|
||||
try:
|
||||
bot_config_path = os.path.join(BotConfig.get_config_dir(), "bot_config.toml")
|
||||
global_config = BotConfig.load_config(config_path=bot_config_path)
|
||||
return {"message": "配置重载成功", "status": "success"}
|
||||
except FileNotFoundError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"重载配置时发生错误: {str(e)}")
|
||||
3
src/plugins/config_reload/test.py
Normal file
3
src/plugins/config_reload/test.py
Normal file
@@ -0,0 +1,3 @@
|
||||
import requests
|
||||
response = requests.post("http://localhost:8080/api/reload-config")
|
||||
print(response.json())
|
||||
Reference in New Issue
Block a user