admin管理员组

文章数量:1287511

I have this application and app.exception_handler correctly handles the exceptions that arise. There is one problem though, i.e., it does not stop the exception to be displayed in the stdout. Is there any way that I could prevent the exceptions from being displayed in the stdout?

import logging

from ecs_logging import StdlibFormatter
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

# Hacer que ignore las excepciones, aún así las sigue haciendo.
logging.raiseExceptions = False

# Create a handler
logHandler = logging.StreamHandler()

# Create an ECS formatter
formatter = StdlibFormatter()

# Attach the formatter to the handler
logHandler.setFormatter(formatter)

# El nivel de log a registrar es dependiente del entorno en el que estemos.
logging.basicConfig(
    level=getattr(logging, 'INFO', logging.INFO),
    handlers=[logHandler]
)

app = FastAPI()


@app.exception_handler(Exception)
async def custom_exception_handler(request: Request, exc: Exception):
    logging.error(f"An error occurred: {exc}")
    return JSONResponse(
        status_code=500,
        content={"message": "An internal server error occurred."},
    )


@app.get("/")
async def read_root():
    raise Exception("This is a test exception")


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8001)

I have this application and app.exception_handler correctly handles the exceptions that arise. There is one problem though, i.e., it does not stop the exception to be displayed in the stdout. Is there any way that I could prevent the exceptions from being displayed in the stdout?

import logging

from ecs_logging import StdlibFormatter
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

# Hacer que ignore las excepciones, aún así las sigue haciendo.
logging.raiseExceptions = False

# Create a handler
logHandler = logging.StreamHandler()

# Create an ECS formatter
formatter = StdlibFormatter()

# Attach the formatter to the handler
logHandler.setFormatter(formatter)

# El nivel de log a registrar es dependiente del entorno en el que estemos.
logging.basicConfig(
    level=getattr(logging, 'INFO', logging.INFO),
    handlers=[logHandler]
)

app = FastAPI()


@app.exception_handler(Exception)
async def custom_exception_handler(request: Request, exc: Exception):
    logging.error(f"An error occurred: {exc}")
    return JSONResponse(
        status_code=500,
        content={"message": "An internal server error occurred."},
    )


@app.get("/")
async def read_root():
    raise Exception("This is a test exception")


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8001)
Share Improve this question edited Feb 27 at 17:14 Chris 34.6k10 gold badges100 silver badges239 bronze badges asked Feb 24 at 15:05 Javi TorreJavi Torre 82416 silver badges36 bronze badges 2
  • Does this help? – Chris Commented Feb 25 at 15:28
  • The way to prevent the exception from being shown in the terminal is to use a try-except block, as demonstrated here and here – Chris Commented Feb 28 at 7:01
Add a comment  | 

1 Answer 1

Reset to default 1

When you use a custom exception handler in FastAPI to return a JSON response, it does not stop uvicorn from logging the exception details (stack trace) to stdout. This happens because uvicorn has its own logging mechanism that prints errors by default. Here are two approaches to prevent the exception details from being output to stdout:

import logging
import uvicorn

# Replace uvicorn.error logger's handlers with a NullHandler
logging.getLogger("uvicorn.error").handlers = [logging.NullHandler()]

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8001)

or simply add thie param to uvicorn

uvicorn main:app --log-level critical

本文标签: python 3xHow to prevent FastAPI from sending the exceptions to stdoutStack Overflow