Files
xiaoxia-saas/docs/PERFORMANCE-MONITORING.md
T
Xiaoxia AI 9c9818a4b1
Deploy / Deploy Staging (push) Failing after 6s
Deploy / Deploy Production (push) Has been skipped
Tests / test (push) Failing after 23s
Tests / lint (push) Failing after 22s
feat(monitoring): add performance monitoring and enhanced logging
- Add PerformanceMonitoringMiddleware for request tracking
- Generate unique request ID for each request
- Log slow requests (threshold configurable, default 1s)
- Add DatabaseQueryLogger for slow query detection
- Add X-Request-ID and X-Process-Time headers
- Comprehensive performance monitoring documentation
- Include optimization strategies and best practices

Phase 4 Task 42/68 completed
2026-06-17 08:36:11 +08:00

188 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 性能监控指南
## 📊 概述
小虾 SaaS 内置了完整的性能监控系统,帮助识别和优化性能瓶颈。
---
## 🔍 监控指标
### 1. 请求性能监控
每个请求自动记录:
- 响应时间
- 请求 ID(用于追踪)
- HTTP 状态码
- 慢请求告警
**响应头:**
```
X-Request-ID: 123e4567-e89b-12d3-a456-426614174000
X-Process-Time: 0.123
```
### 2. 数据库查询监控
自动监控:
- 查询次数
- 查询耗时
- 慢查询(>100ms
### 3. 连接池监控
实时监控:
- 活跃连接数
- 空闲连接数
- 连接池使用率
---
## 🚨 慢请求告警
### 配置阈值
```python
# apps/api/main.py
app.add_middleware(
PerformanceMonitoringMiddleware,
slow_request_threshold=1.0, # 1 秒
)
```
### 日志示例
```
WARNING: Slow request detected: GET /api/v1/projects
took 2.456s (threshold: 1.0s) [request_id=abc123]
```
---
## 📈 性能指标接口
### 获取连接池状态
```http
GET /api/v1/monitoring/pool-stats
Response:
{
"active_connections": 5,
"idle_connections": 3,
"max_connections": 10,
"usage_percent": 50.0
}
```
### 获取性能统计
```http
GET /api/v1/monitoring/performance
Response:
{
"requests_last_hour": 1523,
"avg_response_time": 0.045,
"slow_requests": 12,
"error_rate": 0.02
}
```
---
## 🔧 性能优化建议
### 1. 识别慢请求
查看日志找出慢请求:
```bash
grep "Slow request" logs/app.log
```
### 2. 分析数据库查询
查看慢查询:
```bash
grep "Slow query" logs/app.log
```
### 3. 优化策略
**慢请求优化:**
- 添加缓存(Redis
- 优化业务逻辑
- 使用异步处理
**慢查询优化:**
- 添加数据库索引
- 优化 SQL 查询
- 减少 N+1 查询
**连接池优化:**
- 调整 `maxconn` 配置
- 检查连接泄漏
- 优化连接复用
---
## 📊 监控最佳实践
### 1. 设置告警
```python
# 慢请求告警
if process_time > 1.0:
send_alert(f"Slow request: {request.url}")
# 错误率告警
if error_rate > 0.05: # 5%
send_alert(f"High error rate: {error_rate}")
```
### 2. 定期审查
- 每日检查慢请求日志
- 每周审查性能趋势
- 每月优化瓶颈
### 3. 压力测试
```bash
# 使用 Apache Bench
ab -n 1000 -c 10 http://localhost:8000/api/v1/workspaces
# 使用 wrk
wrk -t4 -c100 -d30s http://localhost:8000/api/v1/workspaces
```
---
## 🎯 性能目标
| 指标 | 目标 | 优秀 |
|------|------|------|
| API 平均响应时间 | <200ms | <50ms |
| 数据库查询平均时间 | <50ms | <10ms |
| 慢请求比例 | <5% | <1% |
| 错误率 | <1% | <0.1% |
| 连接池使用率 | <80% | <60% |
---
## 🔗 相关工具
**APM 工具(推荐):**
- New Relic
- Datadog
- Sentry
**开源方案:**
- Prometheus + Grafana
- ELK Stack
- Jaeger (分布式追踪)
---
**最后更新:** 2026-06-17