TBC/tests/logger.py
d-robotics 633a797226 AutoFlow v2.0: 合并 Test (Robogo) + data-loop-automation (D-Cloud) 为统一平台
- 16 个业务模块,856 个测试用例,40 个 E2E 测试
- 单一 React 19 前端 + PlatformSwitcher 二合一切换
- Flask 后端支持 scenario/dcloud_module/dcloud_e2e/dcloud_all 四种任务类型
- E2E 测试面板:API 全链路(8条) + UI 点击(3条) + 分步测试(3个)
- SSE 实时日志流 + 飞书告警 + 定时调度
- 完整还原原 ToB 平台 TestPanel E2E 模块
2026-06-23 11:48:29 +08:00

130 lines
3.6 KiB
Python
Raw Permalink 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.

"""公共日志配置模块
提供统一的日志配置,支持:
- 控制台输出(INFO 级别,简洁格式)
- 文件输出(DEBUG 级别,紧凑格式)
- 记录当前测试用例名称
- 中文日志支持
- 按日期分割日志文件
"""
import logging
import sys
from datetime import datetime
from pathlib import Path
from contextvars import ContextVar
# 日志目录
LOG_DIR = Path(__file__).parent.parent / "logs"
LOG_DIR.mkdir(exist_ok=True)
# 当前测试用例名称(通过 pytest hook 设置)
_current_test: ContextVar[str] = ContextVar("current_test", default="")
def set_current_test(test_name: str):
"""设置当前测试用例名称"""
_current_test.set(test_name)
def get_current_test() -> str:
"""获取当前测试用例名称"""
return _current_test.get()
class CompactFormatter(logging.Formatter):
"""紧凑格式化器 - 单行输出,包含测试用例名称"""
def format(self, record):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
level = record.levelname
name = record.name
message = record.getMessage()
# 将多行消息压缩为单行
message = message.replace("\n", " | ")
# 获取当前测试用例名称
test_name = get_current_test()
if test_name:
return f"[{timestamp}] [{level}] [{test_name}] {name} - {message}"
return f"[{timestamp}] [{level}] {name} - {message}"
class ConsoleFormatter(logging.Formatter):
"""控制台格式化器 - 简洁单行格式"""
def format(self, record):
timestamp = datetime.now().strftime("%H:%M:%S")
level = record.levelname
message = record.getMessage()
# 控制台只显示时间和消息
level_colors = {
"DEBUG": "\033[36m", # 青色
"INFO": "\033[32m", # 绿色
"WARNING": "\033[33m", # 黄色
"ERROR": "\033[31m", # 红色
}
reset = "\033[0m"
color = level_colors.get(level, "")
# 多行消息压缩为单行
message = message.replace("\n", " | ")
# 获取当前测试用例名称
test_name = get_current_test()
if test_name:
return f"{color}[{timestamp}]{reset} [{test_name}] {message}"
return f"{color}[{timestamp}]{reset} {message}"
def get_logger(name: str = None) -> logging.Logger:
"""获取配置好的 logger 实例
Args:
name: logger 名称,通常使用 __name__
Returns:
配置好的 Logger 实例
"""
logger = logging.getLogger(name)
# 避免重复配置
if logger.handlers:
return logger
logger.setLevel(logging.DEBUG)
# 控制台处理器 - INFO 级别,简洁格式
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(ConsoleFormatter())
logger.addHandler(console_handler)
# 文件处理器 - DEBUG 级别,紧凑格式
today = datetime.now().strftime("%Y-%m-%d")
log_file = LOG_DIR / f"api_{today}.log"
file_handler = logging.FileHandler(log_file, encoding="utf-8")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(CompactFormatter())
logger.addHandler(file_handler)
return logger
def get_api_logger() -> logging.Logger:
"""获取 API 专用的 logger 实例"""
return get_logger("API")
def get_ui_logger() -> logging.Logger:
"""获取 UI 操作专用的 logger 实例"""
return get_logger("UI")
# 预创建常用 logger,方便直接使用
log_api = get_api_logger()
log_ui = get_ui_logger()