You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI+Uvicorn未捕获错误的日志记录/显示位置咨询

FastAPI+Uvicorn未捕获异常日志不显示的问题解决

你遇到的情况是FastAPI默认的异常处理机制会拦截未捕获的异常,仅返回500响应,但不会将异常栈信息输出到Uvicorn的终端日志中,所以只能看到print的内容,看不到错误详情。

解决方法

1. 自定义全局异常处理器

通过自定义异常处理器,使用Python的logging模块将异常栈记录到日志,Uvicorn会捕获这些日志并输出到终端:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import logging

# 配置日志级别,确保能输出异常栈
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

app = FastAPI()

@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    # 记录完整异常栈信息
    logger.exception("未捕获的服务器异常")
    return JSONResponse(
        status_code=500,
        content={"detail": "服务器内部错误"},
    )

@app.post("/events")
def create_events():
    print("entering create_events()")
    raise Exception("an error")

2. 禁用FastAPI默认异常处理(不推荐)

如果不需要FastAPI的JSON格式错误响应,可以移除默认的异常中间件,让Uvicorn直接处理异常并输出日志:

from fastapi import FastAPI
from fastapi.middleware.exceptions import ExceptionMiddleware

app = FastAPI()
# 移除默认异常中间件
app.user_middleware = [mw for mw in app.user_middleware if mw.cls != ExceptionMiddleware]

@app.post("/events")
def create_events():
    print("entering create_events()")
    raise Exception("an error")

这种方式下,Uvicorn会在终端输出完整的错误栈,但返回的响应会是Uvicorn默认的500页面,而非JSON格式。

验证效果

修改代码后,用原启动命令启动Uvicorn:

uvicorn api.main:app --reload --log-level=debug

再次发起POST请求,终端会输出包含异常栈的日志信息,类似:

ERROR:__main__:未捕获的服务器异常
Traceback (most recent call last):
  File "...", line ..., in global_exception_handler
    raise exc
  File "...", line ..., in create_events
    raise Exception("an error")
Exception: an error

内容的提问来源于stack exchange,提问作者rlandster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 09:05:09