簡體   English   中英

Python 在 Fastapi 應用程序上使用 loguru-log 請求參數進行日志記錄

[英]Python Logging with loguru- log request params on Fastapi app

我有一個 fastapi 應用程序,我想記錄對它發出的每個請求。 我正在嘗試為此使用 loguru 和 uvicorn,但我不知道如何打印與每個請求關聯的標頭和請求參數(如果有的話)。

我想要這樣的東西:

INFO 2020-08-13 13:36:33.494 uvicorn.protocols.http.h11_impl:send - 127.0.0.1:52660 - "GET 
/url1/url2/ HTTP/1.1" 400 params={"some": value, "some1":value}

有辦法嗎? 謝謝你的幫助。

這里有一些鏈接:

loguru uvicorn fastapi

您可以使用中間件來記錄每個請求:

import sys

import uvicorn

from fastapi import FastAPI, Request
from loguru import logger
from starlette.routing import Match

logger.remove()
logger.add(sys.stdout, colorize=True, format="<green>{time:HH:mm:ss}</green> | {level} | <level>{message}</level>")
app = FastAPI()


@app.middleware("http")
async def log_middle(request: Request, call_next):
    logger.debug(f"{request.method} {request.url}")
    routes = request.app.router.routes
    logger.debug("Params:")
    for route in routes:
        match, scope = route.matches(request)
        if match == Match.FULL:
            for name, value in scope["path_params"].items():
                logger.debug(f"\t{name}: {value}")
    logger.debug("Headers:")
    for name, value in request.headers.items():
        logger.debug(f"\t{name}: {value}")

    response = await call_next(request)
    return response


@app.get("/{param1}/{param2}")
async def path_operation(param1: str, param2: str):
    return {'param1': param1, 'param2': param2}


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

更新:還可以使用對路由器級別的依賴(感謝下面評論中的@lsabi):

import sys

import uvicorn

from fastapi import FastAPI, Request, APIRouter, Depends
from loguru import logger
from starlette.routing import Match

logger.remove()
logger.add(sys.stdout, colorize=True, format="<green>{time:HH:mm:ss}</green> | {level} | <level>{message}</level>")
app = FastAPI()

router = APIRouter()


async def logging_dependency(request: Request):
    logger.debug(f"{request.method} {request.url}")
    logger.debug("Params:")
    for name, value in request.path_params.items():
        logger.debug(f"\t{name}: {value}")
    logger.debug("Headers:")
    for name, value in request.headers.items():
        logger.debug(f"\t{name}: {value}")


@router.get("/{param1}/{param2}")
async def path_operation(param1: str, param2: str):
    return {'param1': param1, 'param2': param2}

app.include_router(router, dependencies=[Depends(logging_dependency)])

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

curl http://localhost:8001/admin/home

Output:

16:06:43 | DEBUG | GET http://localhost:8001/admin/home
16:06:43 | DEBUG | Params:
16:06:43 | DEBUG |  param1: admin
16:06:43 | DEBUG |  param2: home
16:06:43 | DEBUG | Headers:
16:06:43 | DEBUG |  host: localhost:8001
16:06:43 | DEBUG |  user-agent: curl/7.64.0
16:06:43 | DEBUG |  accept: */*

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM