| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- """
- 请求日志记录器 - 记录每个语音对话请求的详细信息
- """
- import os
- import time
- from datetime import datetime
- from threading import Lock
- from typing import Optional
- class RequestLogger:
- """请求日志记录器(线程安全)"""
-
- def __init__(self, log_file: str = "conversation_log.txt"):
- """
- 初始化日志记录器
-
- Args:
- log_file: 日志文件路径
- """
- self.log_file = log_file
- self.lock = Lock()
-
- # 如果文件不存在,创建并写入表头
- if not os.path.exists(log_file):
- self._write_header()
-
- def _write_header(self):
- """写入日志文件表头"""
- with open(self.log_file, 'w', encoding='utf-8') as f:
- f.write("=" * 120 + "\n")
- f.write("Tolan AI 对话日志\n")
- f.write("格式: 时间 | 用户语音文本 | 录音结束→首个音频时间(ms) | AI输出文本\n")
- f.write("=" * 120 + "\n\n")
-
- def log_request(
- self,
- user_text: str,
- ai_response: str,
- first_audio_latency: Optional[float] = None,
- request_id: Optional[str] = None
- ):
- """
- 记录一条对话请求
-
- Args:
- user_text: 用户语音识别的文本
- ai_response: AI的完整回复文本
- first_audio_latency: 录音结束到首个音频的延迟(毫秒)
- request_id: 请求ID(可选)
- """
- with self.lock:
- # 获取当前时间
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
-
- # 处理延迟信息
- latency_str = f"{first_audio_latency:.0f}ms" if first_audio_latency else "N/A"
-
- # 清理文本(移除换行符,保持单行)
- user_text_clean = user_text.replace('\n', ' ').replace('\r', ' ').strip()
- ai_response_clean = ai_response.replace('\n', ' ').replace('\r', ' ').strip()
-
- # 构建日志行
- log_line = f"{timestamp} | {user_text_clean} | {latency_str} | {ai_response_clean}\n"
-
- # 写入文件
- try:
- with open(self.log_file, 'a', encoding='utf-8') as f:
- f.write(log_line)
-
- print(f"📝 已记录对话日志 [{request_id or 'unknown'}]: {user_text_clean[:20]}... → {ai_response_clean[:20]}...")
- except Exception as e:
- print(f"⚠️ 写入日志失败: {e}")
-
- def log_error(self, user_text: str, error_message: str, request_id: Optional[str] = None):
- """
- 记录错误请求
-
- Args:
- user_text: 用户语音识别的文本
- error_message: 错误信息
- request_id: 请求ID(可选)
- """
- with self.lock:
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- user_text_clean = user_text.replace('\n', ' ').replace('\r', ' ').strip()
- error_clean = error_message.replace('\n', ' ').replace('\r', ' ').strip()
-
- log_line = f"{timestamp} | {user_text_clean} | ERROR | {error_clean}\n"
-
- try:
- with open(self.log_file, 'a', encoding='utf-8') as f:
- f.write(log_line)
-
- print(f"📝 已记录错误日志 [{request_id or 'unknown'}]: {error_clean}")
- except Exception as e:
- print(f"⚠️ 写入错误日志失败: {e}")
- # 全局单例
- request_logger = RequestLogger()
|