mirror of
https://github.com/BoardWare-Genius/jarvis-models.git
synced 2025-12-12 16:23:26 +00:00
fix loki for server
This commit is contained in:
@ -45,6 +45,14 @@ log:
|
||||
time_format: "%Y-%m-%d %H:%M:%S"
|
||||
filename: "D:/Workspace/Logging/jarvis/jarvis-models.log"
|
||||
|
||||
loki:
|
||||
url: "https://loki.bwgdi.com/loki/api/v1/push"
|
||||
labels:
|
||||
app: jarvis
|
||||
env: dev
|
||||
location: "gdi"
|
||||
layer: models
|
||||
|
||||
melotts:
|
||||
mode: local # or docker
|
||||
url: http://10.6.44.141:18080/convert/tts
|
||||
|
||||
37
server.py
37
server.py
@ -9,6 +9,7 @@ import logging
|
||||
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from injector import Injector
|
||||
import yaml
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
@ -23,11 +24,18 @@ app.add_middleware(
|
||||
injector = Injector()
|
||||
blackbox_factory = injector.get(BlackboxFactory)
|
||||
|
||||
with open(".env.yaml", "r") as f:
|
||||
config = yaml.safe_load(f)
|
||||
logger = LokiLogger(
|
||||
tags={"application": "Server", "env": "Development", "source": "python-fastapi-app"},
|
||||
# url=config["loki"]["url"],
|
||||
# username=config["loki"]["username"],
|
||||
# password=config["loki"]["password"],
|
||||
tags=config["loki"]["labels"],
|
||||
logger_name=__name__,
|
||||
level=logging.DEBUG
|
||||
).get_logger()
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def catch_all_exceptions(request: Request, exc: Exception):
|
||||
"""
|
||||
@ -48,37 +56,32 @@ async def catch_all_exceptions(request: Request, exc: Exception):
|
||||
content={"message": "Internal Server Error", "detail": "An unexpected error occurred."}
|
||||
)
|
||||
|
||||
@app.get("/trigger-error")
|
||||
async def trigger_error():
|
||||
"""
|
||||
这个端点会故意抛出一个异常来测试全局异常处理器。
|
||||
"""
|
||||
logger.info("尝试触发错误...")
|
||||
raise ValueError("这是一个测试错误,用于演示全局异常处理。")
|
||||
|
||||
@app.post("/")
|
||||
@app.get("/")
|
||||
async def blackbox(blackbox_name: Union[str, None] = None, request: Request = None):
|
||||
if not blackbox_name:
|
||||
return await JSONResponse(content={"error": "blackbox_name is required"}, status_code=status.HTTP_400_BAD_REQUEST)
|
||||
return JSONResponse(content={"error": "blackbox_name is required"}, status_code=status.HTTP_400_BAD_REQUEST)
|
||||
try:
|
||||
box = blackbox_factory.get_blackbox(blackbox_name)
|
||||
except ValueError:
|
||||
return await JSONResponse(content={"error": "value error"}, status_code=status.HTTP_400_BAD_REQUEST)
|
||||
except ValueError as e:
|
||||
logger.error(f"获取 blackbox 失败: {blackbox_name} - {e}", exc_info=True)
|
||||
return JSONResponse(content={"error": "value error"}, status_code=status.HTTP_400_BAD_REQUEST)
|
||||
try:
|
||||
response = await box.fast_api_handler(request)
|
||||
# 检查响应的状态码,如果 >= 400,则认为是错误响应并记录
|
||||
if response.status_code >= 400:
|
||||
try:
|
||||
response_content_bytes = await response.body()
|
||||
decoded_content = response_content_bytes.decode('utf-8', errors='ignore')
|
||||
try:
|
||||
decoded_content = response.body.decode('utf-8', errors='ignore')
|
||||
logger.error(f"Blackbox 返回错误响应: URL={request.url}, Method={request.method}, Status={response.status_code}, Content={decoded_content}")
|
||||
except Exception as body_exc:
|
||||
logger.error(f"Blackbox {blackbox_name} 返回错误响应: URL={request.url}, Method={request.method}, Status={response.status_code}, 无法解析响应内容: {body_exc}")
|
||||
return response
|
||||
except Exception as e:
|
||||
logger.error(f"Blackbox handler 内部抛出异常: URL={request.url}, Method={request.method}, 异常: {e}", exc_info=True)
|
||||
raise e
|
||||
logger.error(f"Blackbox 内部抛出异常: URL={request.url}, Method={request.method}, 异常报错: {type(e).__name__}: {e}", exc_info=True)
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={"message": "Internal Server Error", "detail": "An unexpected error occurred."}
|
||||
)
|
||||
|
||||
# @app.get("/audio/{filename}")
|
||||
# async def serve_audio(filename: str):
|
||||
|
||||
@ -69,7 +69,7 @@ class LokiLogger:
|
||||
url=self._url,
|
||||
tags=self._tags,
|
||||
version="1", # 通常Loki API版本为1
|
||||
# auth=auth
|
||||
auth=auth
|
||||
)
|
||||
self._logger.addHandler(loki_handler)
|
||||
# 同时添加一个StreamHandler到控制台,以便在本地调试时也能看到日志输出
|
||||
|
||||
Reference in New Issue
Block a user