增强日志

This commit is contained in:
zj
2026-03-02 15:50:51 +08:00
parent e16578a304
commit deb4fa0e79
5 changed files with 384 additions and 25 deletions

View File

@@ -161,13 +161,98 @@ def setup_logging(
if log_file:
os.makedirs(os.path.dirname(log_file) or '.', exist_ok=True)
file_handler = logging.FileHandler(log_file)
# 使用 FileHandler 并设置立即刷新
file_handler = logging.FileHandler(log_file, mode='a')
file_handler.setFormatter(formatter)
# 确保每次日志写入后立即刷新到磁盘
file_handler.flush = lambda: file_handler.stream.flush()
logger.addHandler(file_handler)
return logger
class ProgressLogger:
"""
进度日志记录器 - 用于记录测试进度,便于中断后排查问题。
"""
def __init__(self, log_file: Optional[str] = None):
self.logger = logging.getLogger(__name__)
self.log_file = log_file
self.steps = []
self.current_step = None
self.start_time = None
def start(self, operation: str):
"""开始一个操作步骤。"""
from datetime import datetime
self.current_step = {
"operation": operation,
"start_time": datetime.now().isoformat(),
"status": "running"
}
self.start_time = datetime.now()
msg = f"[START] {operation}"
self.logger.info(msg)
self._flush_log()
def end(self, status: str = "success", message: str = ""):
"""结束当前操作步骤。"""
from datetime import datetime
if self.current_step:
end_time = datetime.now()
duration = (end_time - self.start_time).total_seconds() if self.start_time else 0
self.current_step["end_time"] = end_time.isoformat()
self.current_step["status"] = status
self.current_step["duration_seconds"] = duration
self.current_step["message"] = message
self.steps.append(self.current_step)
msg = f"[END] {self.current_step['operation']} - Status: {status}"
if message:
msg += f" - {message}"
msg += f" (Duration: {duration:.2f}s)"
if status == "error":
self.logger.error(msg)
elif status == "warning":
self.logger.warning(msg)
else:
self.logger.info(msg)
self._flush_log()
self.current_step = None
def log(self, message: str, level: str = "info"):
"""记录中间日志。"""
msg = f"[PROGRESS] {self.current_step['operation'] if self.current_step else 'UNKNOWN'} - {message}"
if level == "error":
self.logger.error(msg)
elif level == "warning":
self.logger.warning(msg)
elif level == "debug":
self.logger.debug(msg)
else:
self.logger.info(msg)
self._flush_log()
def _flush_log(self):
"""强制刷新日志到磁盘。"""
for handler in self.logger.handlers:
if hasattr(handler, 'flush'):
handler.flush()
def get_summary(self) -> Dict[str, Any]:
"""获取执行摘要。"""
return {
"total_steps": len(self.steps),
"steps": self.steps,
"current_running": self.current_step
}
def parse_key_value_output(text: str, delimiter: str = ':') -> Dict[str, str]:
"""
解析 key: value 格式的文本输出。