How to implement request logging and monitoring in FastAPI
Introduction:
FastAPI is a high-performance web framework based on Python 3.7, which provides many powerful functions and features, including automated requests and response model verification, security, performance optimization, etc. In actual development, we often need to record request logs in the application for debugging and monitoring analysis. This article will introduce how to implement request logging and monitoring in FastAPI and provide corresponding code examples.
1. Install dependency packages
Before we start, we need to install some necessary dependency packages. Open the terminal and execute the following command:
pip install fastapi uvicorn loguru
Among them, loguru is an easy-to-use logging library, we will use it to record request logs.
2. Create a FastAPI application
First, we need to create a FastAPI application. In the project directory, create a file named main.py and write the following code:
from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"}
3. Record the request log
Next, we will use the loguru library to record the request log. Add the following code to the main.py file:
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)
In the above code, we first import the logger object of the loguru library and add a file logger. We specified the path of the log file as logs/request.log and set the maximum size of the log file to 10MB. Then, in the root() function, we use the logger.info() method to log the request.
4. Start the application
Save the main.py file and return to the terminal, execute the following command to start the FastAPI application:
uvicorn main:app --reload
The terminal will output the access URL of the application, such as http: //127.0.0.1:8000. Accessing this URL in the browser we will see the "Hello World" message. Open the logs/request.log file and we will see the request log records.
5. Monitoring requests
In addition to recording request logs, we can also monitor the processing time and status code of the request. In order to implement this function, we need to use the Middleware provided by FastAPI. Add the following code to the main.py file:
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)
In the above code, we first import the time module and add a sleep time to the root() function to simulate the request processing time. Then, we added the logic to calculate the request processing time and record the request status code in the log_request() middleware function. In the shutdown_event() function, we delete the previously added logger.
Now, restart the FastAPI application and visit the application URL in your browser. Refresh the page in the browser and open the logs/request.log file. We will see the request log records including the request method, URL, status code and processing time.
Conclusion:
This article introduces how to implement request logging and monitoring in FastAPI. We use the loguru library to record request logs, and use FastAPI's Middleware to monitor the request processing time and status code. These features allow us to better track and monitor application requests and responses. The above is a code example to implement request logging and monitoring.
Reference materials:
The above is the detailed content of How to implement request logging and monitoring in FastAPI. For more information, please follow other related articles on the PHP Chinese website!