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
|
1 Answer
Reset to default 1When 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
版权声明:本文标题:python 3.x - How to prevent FastAPI from sending the exceptions to stdout - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741258327a2367120.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
try-except
block, as demonstrated here and here – Chris Commented Feb 28 at 7:01