FastAPI 日志管理
基本配置
使用 loguru 作为日志库,输出到控制台,不写文件:
错误记录
对于异常,使用 logger.exception(e) 记录完整堆栈:
AsyncIO 调试模式
排查异步阻塞问题时,启用 AsyncIO debug 模式。当某个任务耗时超过 100ms 时会打印警告:
输出示例:
这能帮你快速定位哪个 async def 路由里写了阻塞调用。
请求日志中间件
如需记录每个请求的耗时,用纯 ASGI 中间件(不用 BaseHTTPMiddleware,性能更好):
import time
from loguru import logger
class RequestLogMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
start = time.perf_counter()
await self.app(scope, receive, send)
elapsed = time.perf_counter() - start
logger.info(f"{scope['method']} {scope['path']} {elapsed:.3f}s")
app.add_middleware(RequestLogMiddleware)