如何在FastAPI中實現請求日誌記錄和監控
引言:
FastAPI是一個基於Python 3.7 的高效能Web框架,它提供了許多強大的功能和特性,包括自動化的請求和響應模型驗證、安全性、效能最佳化等。在實際開發中,我們經常需要在應用程式中記錄請求日誌以便進行排錯和監控分析。本文將介紹如何在FastAPI中實作請求日誌記錄和監控,並提供對應的程式碼範例。
一、安裝依賴套件
在開始之前,我們需要先安裝一些必要的依賴套件。開啟終端,執行以下指令:
pip install fastapi uvicorn loguru
其中,loguru是一個易用的日誌記錄庫,我們將使用它來記錄請求日誌。
二、建立一個FastAPI應用程式
首先,我們需要建立一個FastAPI應用程式。在專案目錄下,建立一個名為main.py的文件,並寫入以下程式碼:
from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"}
三、記錄請求日誌
接下來,我們將使用loguru函式庫來記錄請求日誌。在main.py檔案中加入以下程式碼:
from loguru import logger import uvicorn from fastapi import FastAPI app = FastAPI() @app.on_event("startup") async def startup_event(): logger.add("logs/request.log", rotation="10 MB") @app.get("/") async def root(): logger.info("Hello World") return {"message": "Hello World"} if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000)
上述程式碼中,我們首先匯入loguru庫的logger對象,並新增一個檔案日誌記錄器。我們指定了記錄日誌檔案的路徑為logs/request.log,並設定了日誌檔案的最大大小為10MB。然後,在root()函數中,我們使用logger.info()方法記錄請求日誌。
四、啟動應用程式
儲存main.py檔案並返回終端,執行以下命令啟動FastAPI應用程式:
uvicorn main:app --reload
終端將輸出應用程式的存取URL,如http: //127.0.0.1:8000。在瀏覽器中造訪該URL,我們將看到"Hello World"訊息。開啟logs/request.log文件,我們將看到請求日誌的記錄。
五、監控請求
除了記錄請求日誌,我們還可以監控請求的處理時間和狀態碼。為了實現這個功能,我們需要使用FastAPI提供的Middleware。在main.py檔案中加入以下程式碼:
from loguru import logger import time import uvicorn from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware app = FastAPI() @app.on_event("startup") async def startup_event(): logger.add("logs/request.log", rotation="10 MB") @app.on_event("shutdown") async def shutdown_event(): logger.remove(handler_id="request_logger") @app.middleware("http") async def log_request(request: Request, call_next): start_time = time.time() response = await call_next(request) process_time = time.time() - start_time logger.info( "Request: {method} {url} {status_code} {process_time:.2f}ms", method=request.method, url=request.url, status_code=response.status_code, process_time=process_time * 1000, ) return response @app.get("/") async def root(): logger.info("Hello World") return {"message": "Hello World"} if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000)
上述程式碼中,我們首先匯入time模組,並在root()函數中新增了一個睡眠時間,以模擬請求處理時間。然後,我們在log_request()中間件函數中加入了計算請求處理時間和記錄請求狀態碼的邏輯。在shutdown_event()函數中,我們刪除了先前新增的日誌記錄器。
現在,重新啟動FastAPI應用程序,並在瀏覽器中存取應用程式的URL。在瀏覽器中刷新頁面,打開logs/request.log文件,我們將看到包含請求方法、URL、狀態碼和處理時間的請求日誌記錄。
結論:
本文介紹如何在FastAPI中實作請求日誌記錄和監控。我們使用loguru函式庫來記錄請求日誌,並藉助FastAPI的Middleware來監控請求的處理時間和狀態碼。透過這些功能,我們可以更好地追蹤和監控應用程式的請求和回應。以上就是實作請求日誌記錄和監控的程式碼範例。
參考資料:
- FastAPI官方文件:https://fastapi.tiangolo.com/
- loguru官方文件:https://loguru.readthedocs. io/
以上是如何在FastAPI中實現請求日誌記錄和監控的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。

toAccesselementsInapythonlist,useIndIndexing,負索引,切片,口頭化。 1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

Atom編輯器mac版下載
最受歡迎的的開源編輯器

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中