Loading

在 FastAPI 中使用异常处理器记录日志

记录一下如何在 FastAPI 中处理日志,方便后续 Copy 代码

安装 FastAPI

> python3.11 -m venv venv
> source venv/bin/activate
> pip install fastapi "uvicorn[standard]"

启动 FastAPI

编写一个小 DEMO

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def home():
    return {"message": "Hello, World!"}

添加日志

import logging
from fastapi import FastAPI


app = FastAPI()

uvicorn_log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

logging.basicConfig(
    format=uvicorn_log_format,
    level=logging.INFO
)
logger = logging.getLogger("LOGGER")


@app.get("/")
async def home():
    logger.info("Home page visited")
    return {"message": "Hello, World!"}

使用异常处理器

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


app = FastAPI()

uvicorn_log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

logging.basicConfig(
    format=uvicorn_log_format,
    level=logging.INFO
)
logger = logging.getLogger("LOGGER")


class AuthException(Exception):
    ...


@app.exception_handler(AuthException)
async def auth_exception_handler(_request: Request, exc: AuthException):
    logger.error(str(exc))
    return JSONResponse(
        status_code=200,
        content={"message": "Authentication failed"}
    )


@app.get("/chat")
async def chat():
    message = mock_request_llama2()
    return dict(message=message)


@app.get("/")
async def home():
    logger.info("Home page visited")
    return {"message": "Hello, World!"}


def mock_request_llama2() -> str:
    if random.random() > 0.5:
        raise AuthException("Authentication failed")

    return "Hello! How can I assist you today?"

效果如下

> uvicorn main:app --reload --host 0.0.0.0 --port 8080
INFO:     Will watch for changes in these directories: ['~/Code/fast']
INFO:     Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
INFO:     Started reloader process [31132] using WatchFiles
INFO:     Started server process [31134]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
2024-03-22 15:29:05,341 - LOGGER - ERROR - Authentication failed
INFO:     127.0.0.1:58222 - "GET /chat HTTP/1.1" 200 OK
2024-03-22 15:29:16,751 - LOGGER - INFO - Home page visited
INFO:     127.0.0.1:58224 - "GET / HTTP/1.1" 200 OK
posted @ 2024-03-22 15:25  kosihpc  阅读(213)  评论(0编辑  收藏  举报