---
description: "FastAPI 日志管理的约定：基本配置、错误记录、AsyncIO 调试模式、请求日志中间件"
---

# FastAPI 日志管理

## 基本配置

使用 loguru 作为日志库，输出到控制台，不写文件：

```python
from loguru import logger
import sys

logger.remove()
logger.add(sys.stderr, level="INFO")
```

## 错误记录

对于异常，使用 `logger.exception(e)` 记录完整堆栈：

```python
try:
    result = await some_operation()
except Exception as e:
    logger.exception(e)
    raise
```

## AsyncIO 调试模式

排查异步阻塞问题时，启用 AsyncIO debug 模式。当某个任务耗时超过 100ms 时会打印警告：

```bash
PYTHONASYNCIODEBUG=1 python main.py
```

输出示例：
```
Executing <Task finished name='Task-3' ...> took 1.009 seconds
```

这能帮你快速定位哪个 `async def` 路由里写了阻塞调用。

## 请求日志中间件

如需记录每个请求的耗时，用纯 ASGI 中间件（不用 BaseHTTPMiddleware，性能更好）：

```python
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)
```
