mirror of
https://github.com/BoardWare-Genius/jarvis-models.git
synced 2025-12-13 16:53:24 +00:00
support loki in server.py
This commit is contained in:
51
server.py
51
server.py
@ -4,6 +4,9 @@ from fastapi import FastAPI, Request, status
|
||||
from fastapi.responses import JSONResponse, Response, StreamingResponse
|
||||
|
||||
from src.blackbox.blackbox_factory import BlackboxFactory
|
||||
from src.log.loki_config import LokiLogger
|
||||
import logging
|
||||
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from injector import Injector
|
||||
|
||||
@ -20,6 +23,39 @@ app.add_middleware(
|
||||
injector = Injector()
|
||||
blackbox_factory = injector.get(BlackboxFactory)
|
||||
|
||||
logger = LokiLogger(
|
||||
tags={"application": "Server", "env": "Development", "source": "python-fastapi-app"},
|
||||
level=logging.DEBUG
|
||||
).get_logger()
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def catch_all_exceptions(request: Request, exc: Exception):
|
||||
"""
|
||||
捕获所有在 ASGI 应用中未被处理的异常,并记录到 Loki。
|
||||
"""
|
||||
logger.error(
|
||||
f"Unhandled exception in ASGI application for path: {request.url.path}, method: {request.method} - {exc}",
|
||||
exc_info=True, # 必须为 True,才能获取完整的堆栈信息
|
||||
extra={
|
||||
"path": request.url.path,
|
||||
"method": request.method,
|
||||
"error_type": type(exc).__name__,
|
||||
"error_message": str(exc)
|
||||
}
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
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):
|
||||
@ -29,7 +65,20 @@ async def blackbox(blackbox_name: Union[str, None] = None, request: Request = No
|
||||
box = blackbox_factory.get_blackbox(blackbox_name)
|
||||
except ValueError:
|
||||
return await JSONResponse(content={"error": "value error"}, status_code=status.HTTP_400_BAD_REQUEST)
|
||||
return await box.fast_api_handler(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')
|
||||
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
|
||||
|
||||
# @app.get("/audio/{filename}")
|
||||
# async def serve_audio(filename: str):
|
||||
|
||||
Reference in New Issue
Block a user