FastAPI + Vue3 自动化测试平台(2)-- 日志中间件
前言
在开发和运行自动化测试平台时,日志功能是至关重要的一部分。日志不仅能帮助我们快速定位和解决问题,还能作为平台运行的记录依据,为后续分析和优化提供参考。
在本篇文章中,我们将介绍如何为 FastAPI 构建一个日志中间件,记录请求日志、错误日志和系统运行日志等关键信息,从而提升系统的可维护性和可观测性。
为什么需要日志中间件?
在一个完整的测试平台中,日志系统主要承担以下功能:
- 记录 API 请求日志:包括请求的时间、URL、方法、参数、响应时间等信息,便于排查问题。
- 捕获错误日志:记录后端的异常和错误,为开发者提供调试依据。
- 记录系统运行日志:包括任务执行、关键操作、资源使用情况等,为系统优化提供数据支持。
- 结构化日志输出:输出 JSON 格式的日志,便于后续存储和分析。
日志中间件的实现
1. 安装依赖
我们将使用 Python 的 loguru
库来实现日志功能。它简单易用,功能强大。
安装 loguru
:
bash
pip install loguru
2.编写日志中间件代码
python
"""日志中间件."""
import json
import os
import sys
from datetime import datetime, timedelta, timezone
from fastapi import Response
from loguru import logger
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
class Logger_Middleware(BaseHTTPMiddleware):
"""日志类."""
async def dispatch(self, request: Request, call_next) -> Response:
"""重写dispatch方法.
Args:
request (Request): Request.
call_next (_type_): 回调函数.
Returns:
Response: Response.
"""
self.logger = logger
method = request.method
# body = await request.body() # 请求体,预留坑位
path = request.scope["path"]
http_type = request.scope["type"]
china_tz = timezone(timedelta(hours=8), "China")
current_time_china = datetime.now(china_tz)
formatted_time = current_time_china.strftime("%Y-%m-%d")
response = await call_next(request)
self.logger.remove()
code = response.status_code
INFO = f"{code}__{method}__{path}"
# 判断请求的响应结果,然后写入log文件
if code != 200:
log_path = os.path.join("./log/error", f"{formatted_time}_error.log")
self.logger.add(
log_path,
encoding='utf-8',
rotation="7 days",
enqueue=True
)
self.logger.error(INFO)
else:
log_path = os.path.join("./log/info", f"{formatted_time}_info.log")
self.logger.add(
log_path,
encoding='utf-8',
rotation="7 days",
enqueue=True
)
self.logger.info(INFO)
return response
3.注册到fastapi的服务中
python
from fastapi import FastAPI
from middlewares.logging_middleware import LoggingMiddleware
# 初始化 FastAPI 应用
app = FastAPI()
# 添加日志中间件
app.middleware("http")(LoggingMiddleware())
4.日志输出示例
python
2024-10-30 10:21:52.452 | INFO | middleware.log_middleware:dispatch:54 - 200__POST__/user/login
2024-10-30 10:23:43.225 | INFO | middleware.log_middleware:dispatch:54 - 200__POST__/user/login
2024-10-30 10:26:30.461 | INFO | middleware.log_middleware:dispatch:54 - 200__POST__/user/login
2024-10-30 10:30:21.039 | INFO | middleware.log_middleware:dispatch:54 - 200__POST__/user/login
2024-10-30 10:47:38.788 | INFO | middleware.log_middleware:dispatch:54 - 200__POST__/user/login
2024-10-30 10:47:51.864 | INFO | middleware.log_middleware:dispatch:54 - 200__POST__/user/login
2024-10-30 10:48:51.512 | INFO | middleware.log_middleware:dispatch:54 - 200__POST__/user/login
2024-10-30 10:49:47.051 | INFO | middleware.log_middleware:dispatch:54 - 200__POST__/user/login
2024-10-30 10:49:50.098 | INFO | middleware.log_middleware:dispatch:54 - 200__POST__/user/login
2024-10-30 10:53:17.336 | INFO | middleware.log_middleware:dispatch:54 - 200__POST__/user/login
2024-10-30 10:53:36.034 | INFO | middleware.log_middleware:dispatch:54 - 200__POST__/user/login
2024-10-30 10:54:30.589 | INFO | middleware.log_middleware:dispatch:54 - 200__POST__/user/login