ai-chat-ui/LOGGING_SYSTEM.md

151 lines
3.5 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.

# 统一日志管理系统说明
## 功能特性
1. **多级别日志支持**DEBUG, INFO, WARNING, ERROR, CRITICAL
2. **结构化日志**支持JSON格式的结构化日志输出
3. **文件轮转**:自动按日期和大小分割日志文件
4. **系统监控**:记录系统状态和性能指标
5. **请求追踪**记录API请求和响应信息
6. **错误追踪**:详细记录异常和错误信息
## 使用方法
### 1. 基本日志记录
```python
from utils.logger import log_debug, log_info, log_warning, log_error, log_critical
log_info("服务启动成功")
log_warning("内存使用率较高")
log_error("API请求失败")
```
### 2. 结构化日志
```python
from utils.logger import log_structured
log_structured(
"info",
"用户登录成功",
user_id="12345",
ip_address="192.168.1.100",
timestamp=datetime.now().isoformat()
)
```
### 3. 请求日志
```python
from utils.logger import log_request_info, log_response_info
log_request_info("POST", "/api/chat", "192.168.1.100", "Mozilla/5.0...")
log_response_info(200, 150.5, "/api/chat", "POST", "192.168.1.100")
```
### 4. 错误详情记录
```python
from utils.logger import log_error_detail
try:
# 可能出错的代码
pass
except Exception as e:
log_error_detail(
type(e).__name__,
str(e),
str(e.__traceback__),
context={"user_id": "123", "action": "chat_request"}
)
```
### 5. 对话交互记录
```python
from utils.logger import log_chat_interaction
log_chat_interaction(
user_input="你好,请帮我分析这张图片",
ai_response="这张图片显示了一座山和一片湖泊",
model="qwen-vl-plus",
conversation_id="conv_abc123"
)
```
### 6. 系统状态记录
```python
from utils.logger import log_system_status
log_system_status(
status="healthy",
uptime=3600.5,
cpu_usage=45.2,
memory_usage=60.8,
disk_usage=75.1
)
```
## 配置
### 环境变量配置
| 环境变量 | 默认值 | 说明 |
|---------|--------|------|
| LOG_LEVEL | INFO | 日志级别 |
| LOG_DIR | logs | 日志文件目录 |
| LOG_MAX_BYTES | 10485760 | 单个日志文件最大大小 |
| LOG_BACKUP_COUNT | 5 | 保留的备份日志数量 |
### 配置文件
创建 `logging.conf` 文件来配置日志系统:
```
LOG_LEVEL=INFO
LOG_DIR=logs
LOG_MAX_BYTES=10485760
LOG_BACKUP_COUNT=5
```
## 日志文件组织
- 日志文件按日期分割:`ai-chat-api_2026-03-03.log`
- 自动轮转,当日志文件达到指定大小时创建新文件
- 保留最近5个日志文件旧文件会被自动删除
- 日志文件存放在 `logs/` 目录下
## 集成到现有代码
在你的 FastAPI 应用中:
```python
from utils.logger import setup_global_logger
# 初始化日志系统
logger = setup_global_logger()
@app.middleware("http")
async def logging_middleware(request, call_next):
start_time = time.time()
# 记录请求
logger.info(f"Request: {request.method} {request.url.path}")
response = await call_next(request)
# 记录响应
process_time = time.time() - start_time
logger.info(f"Response: {response.status_code} in {process_time:.2f}s")
return response
```
## 注意事项
1. 使用结构化日志便于日志分析和查询
2. 避免在日志中记录敏感信息如密码、token等
3. 适当使用日志级别避免过度记录DEBUG信息
4. 定期清理旧的日志文件,防止磁盘空间不足