Spaces:
Sleeping
Sleeping
File size: 8,423 Bytes
fcc1a30 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | """
Supabase 日志使用示例
演示如何在项目中使用 Supabase 日志记录器
"""
from services.supabase_logger import (
get_supabase_logger,
log_api_access,
log_model_performance,
LogPerformance,
log_debug,
log_error
)
from functools import wraps
import time
# ============================================
# 示例 1: 基本日志记录
# ============================================
def example_basic_logging():
"""基本日志记录示例"""
logger = get_supabase_logger()
# 记录 API 访问
logger.log_api_access(
endpoint="/api/v1/chat",
method="POST",
session_id="user_123",
response_time_ms=150,
status_code=200
)
# 记录调试信息
logger.log_debug(
level="INFO",
logger="intelligence_analyzer",
message="Scenario detected: policy_inquiry",
session_id="user_123",
data={
"scenario": "policy_inquiry",
"confidence": 0.95,
"keywords": ["年假", "多少"]
}
)
# 记录错误
logger.log_error(
error_type="model_load",
error_message="Failed to load sentiment model",
error_stack="Traceback...\n File ...",
endpoint="/api/v1/evaluate"
)
# ============================================
# 示例 2: 使用装饰器
# ============================================
@log_api_access("/api/v1/chat")
def process_chat_request(question: str, session_id: str):
"""
使用 API 日志装饰器
自动记录 API 调用和响应时间
"""
# 模拟处理
time.sleep(0.1)
return {"answer": "这是回复内容"}
@log_model_performance("sbert-hr-v2", "sbert")
def encode_with_sbert(text: str):
"""
使用模型性能装饰器
自动记录模型推理性能
"""
# 模拟编码
time.sleep(0.05)
return [0.1, 0.2, 0.3]
# ============================================
# 示例 3: 使用上下文管理器
# ============================================
def example_context_manager():
"""使用上下文管理器追踪性能"""
with LogPerformance("chat_processing", "deepseek-chat", "llm"):
# 执行耗时操作
result = call_llm_api("年假有多少天?")
return result
def call_llm_api(prompt: str):
"""模拟 LLM API 调用"""
time.sleep(0.2)
return "根据规定,年假天数与工龄挂钩..."
# ============================================
# 示例 4: 在 intelligence_analyzer 中集成
# ============================================
def analyze_with_logging(employee_input: str, session_id: str):
"""
在分析器中集成日志记录
"""
logger = get_supabase_logger()
# 记录输入
logger.log_debug(
level="INFO",
logger="intelligence_analyzer",
message=f"Processing input: {employee_input[:50]}...",
session_id=session_id
)
try:
# 场景识别
start_time = time.time()
scenario = detect_scenario(employee_input)
logger.log_debug(
level="INFO",
logger="intelligence_analyzer",
message="Scenario detected",
session_id=session_id,
data={"scenario": scenario, "confidence": 0.9}
)
# 记录用户行为
logger.log_user_behavior(
session_id=session_id,
action_type="chat",
action_detail="scenario_detection",
input_text=employee_input,
scenario_detected=scenario,
success=True
)
return scenario
except Exception as e:
# 记录错误
logger.log_error(
error_type="analysis_error",
error_message=str(e),
session_id=session_id,
user_input=employee_input
)
raise
def detect_scenario(text: str) -> str:
"""模拟场景检测"""
time.sleep(0.02)
return "policy_inquiry"
# ============================================
# 示例 5: 在 FastAPI 路由中集成
# ============================================
from fastapi import Request
async def log_request_middleware(request: Request, call_next):
"""
FastAPI 中间件 - 记录所有请求
"""
logger = get_supabase_logger()
start_time = time.time()
# 处理请求
response = await call_next(request)
# 计算响应时间
process_time = int((time.time() - start_time) * 1000)
# 记录日志
logger.log_api_access(
endpoint=request.url.path,
method=request.method,
client_ip=request.client.host if request.client else None,
user_agent=request.headers.get("user-agent"),
session_id=request.headers.get("x-session-id"),
response_time_ms=process_time,
status_code=response.status_code
)
# 添加响应头
response.headers["X-Process-Time"] = str(process_time)
return response
# ============================================
# 示例 6: 批量日志记录
# ============================================
def batch_log_examples():
"""批量日志记录示例"""
logger = get_supabase_logger()
# 批量记录用户行为
behaviors = [
{
"session_id": "user_1",
"action_type": "chat",
"scenario_detected": "policy_inquiry",
"success": True
},
{
"session_id": "user_1",
"action_type": "chat",
"scenario_detected": "leave_application",
"success": True
},
{
"session_id": "user_2",
"action_type": "evaluate",
"success": False,
"error_message": "Invalid dialogue format"
}
]
for behavior in behaviors:
logger.log_user_behavior(**behavior)
# ============================================
# 示例 7: 错误追踪
# ============================================
def example_with_error_tracking():
"""带错误追踪的示例"""
logger = get_supabase_logger()
try:
# 模拟错误
result = 1 / 0
except Exception as e:
import traceback
# 记录详细错误信息
logger.log_error(
error_type="calculation_error",
error_message=str(e),
error_stack=traceback.format_exc(),
session_id="debug_session",
request_data={"operation": "division", "operands": [1, 0]}
)
# ============================================
# 示例 8: 模型性能追踪
# ============================================
def track_all_models():
"""追踪所有模型的性能"""
logger = get_supabase_logger()
models = {
"sbert": "KarenYYH/sbert-hr-v2",
"sentiment": "KarenYYH/sentiment-hr",
"llm": "deepseek-chat"
}
for model_type, model_name in models.items():
with LogPerformance(f"load_{model_type}", model_name, model_type):
# 模拟模型加载
time.sleep(0.1)
# ============================================
# 简化的日志记录
# ============================================
def example_simplified_logging():
"""使用简化函数记录日志"""
# 调试日志
log_debug("intelligence_analyzer", "处理用户输入", level="INFO",
session_id="user_123", data={"input_length": 20})
# 错误日志
log_error("api_error", "请求超时", endpoint="/api/v1/chat",
session_id="user_123", response_time_ms=5000)
# ============================================
# 运行所有示例
# ============================================
if __name__ == "__main__":
print("运行 Supabase 日志示例...")
example_basic_logging()
print("✓ 基本日志记录")
process_chat_request("年假有多少天?", "user_123")
print("✓ API 日志装饰器")
encode_with_sbert("测试文本")
print("✓ 模型性能装饰器")
example_context_manager()
print("✓ 上下文管理器")
analyze_with_logging("年假有多少天?", "user_456")
print("✓ 分析器集成")
batch_log_examples()
print("✓ 批量日志")
example_with_error_tracking()
print("✓ 错误追踪")
track_all_models()
print("✓ 模型性能追踪")
example_simplified_logging()
print("✓ 简化日志")
print("\n所有示例运行完成!")
|