Files
douyin_guaji-main/douyin/logging/log_formatter.py
T
Your Name efe6e2252f feat: Add logging and error handling enhancements
- Introduced new logging modules for action tracking, error logging, and performance tracking to improve observability.
- Added functions for retrieving debug and error log paths in `path_config.py`.
- Updated various components to utilize the new logging system, enhancing error handling and performance diagnostics.
- Implemented a GUI component for viewing error logs, improving user experience in monitoring application issues.
- Cleaned up unnecessary blank lines and improved code readability across multiple files.
2025-12-29 20:48:09 +08:00

157 lines
4.4 KiB
Python

"""日志格式化与美化模块
纯函数化输出格式,便于在不同日志组件之间复用。
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
def format_debug_log(message: str, level: str = "DEBUG", tag: Optional[str] = None, **fields: Any) -> str:
parts = []
if tag:
parts.append(f"[{tag}]")
parts.append(f"[{level}]")
parts.append(message)
if fields:
kv = " ".join(f"{k}={v}" for k, v in fields.items())
parts.append(kv)
return " ".join(parts)
def format_action_log(action: str, details: Optional[str] = None, **fields: Any) -> str:
base = f"[ACTION] {action}"
if details:
base += f" {details}"
if fields:
base += " " + " ".join(f"{k}={v}" for k, v in fields.items())
return base
def format_error_log(message: str, level: str = "ERROR", tag: Optional[str] = None, **fields: Any) -> str:
"""格式化错误日志"""
parts = []
if tag:
parts.append(f"[{tag}]")
parts.append(f"[{level}]")
parts.append(message)
if fields:
kv = " ".join(f"{k}={v}" for k, v in fields.items())
parts.append(kv)
return " ".join(parts)
def format_call_stack(stack: Optional[List[str]] = None) -> str:
if not stack:
return ""
return "\n".join(stack)
def format_parameters(params: Dict[str, Any]) -> str:
if not params:
return ""
return " ".join(f"{k}={v}" for k, v in params.items())
def format_variables(vars: Dict[str, Any]) -> str:
if not vars:
return ""
return " ".join(f"{k}={v}" for k, v in vars.items())
def format_exception(exc: BaseException) -> str:
import traceback
return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
def add_separators(text: str, label: Optional[str] = None) -> str:
if not label:
label = ""
sep = "=" * 80
return f"{sep}\n {label} \n{sep}\n{text}\n{sep}"
def add_colors(text: str, color: str = "green") -> str:
# 简易颜色支持,只有在控制台启用时有效
colors = {
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"reset": "\033[0m",
}
if color in colors:
return f"{colors[color]}{text}{colors['reset']}"
return text
def beautify_log_output(line: str) -> str:
"""
美化日志输出,为GUI显示优化格式。
对日志行进行美化处理,包括:
- 提取关键信息
- 简化冗余部分
- 突出重要信息
"""
if not line or not line.strip():
return line
# 对于GUI显示,我们保持相对简洁但有用的格式
# 移除过长的堆栈跟踪,但保留关键错误信息
if len(line) > 500:
# 如果行太长,进行截断
parts = line.split()
if len(parts) > 10:
# 保留前10个部分和最后的部分
shortened = " ".join(parts[:8]) + " ... " + " ".join(parts[-2:])
return shortened
# 突出显示重要关键字
important_keywords = ["ERROR", "CRITICAL", "FAILED", "EXCEPTION"]
for keyword in important_keywords:
if keyword in line.upper():
# 在GUI中我们不添加颜色代码,因为GUI使用标签系统
# 这里只是为了标识重要行
break
return line
def colorize_log_line(line: str) -> str:
"""
为日志行添加颜色代码(用于控制台输出)。
基于日志级别和内容为日志行添加ANSI颜色代码。
"""
if not line:
return line
# 检查日志级别并应用相应颜色
if "[DEBUG]" in line:
return add_colors(line, "blue")
elif "[INFO]" in line:
return add_colors(line, "green")
elif "[WARNING]" in line:
return add_colors(line, "yellow")
elif "[ERROR]" in line:
return add_colors(line, "red")
elif "[CRITICAL]" in line:
return add_colors(line, "red") # 红色加粗可以通过多次应用实现
# 检查特殊内容
if "elapsed_seconds=" in line or "耗时" in line:
return add_colors(line, "green")
if "EXCEPTION" in line.upper():
return add_colors(line, "red")
return line
__all__ = [
"format_debug_log",
"format_action_log",
"format_error_log",
"format_call_stack",
"format_parameters",
"format_variables",
"format_exception",
"add_separators",
"add_colors",
"beautify_log_output",
"colorize_log_line",
]