83 lines
2.5 KiB
Python
83 lines
2.5 KiB
Python
# logger_utils.py
|
||
|
||
import queue
|
||
import datetime
|
||
from colorama import Fore, Style, init
|
||
|
||
# 初始化 colorama(仅 Windows 需要)
|
||
init(autoreset=True)
|
||
|
||
# 日志等级颜色映射(控制台 + UI)
|
||
LOG_COLORS = {
|
||
'default': Fore.CYAN,
|
||
'info': Fore.CYAN,
|
||
'loading': Fore.YELLOW,
|
||
'warning': Fore.YELLOW,
|
||
'error': Fore.RED,
|
||
'trigger': Fore.GREEN,
|
||
'debug': Fore.BLUE,
|
||
}
|
||
|
||
# 【新增】UI 样式映射
|
||
# LOG_STYLES = {
|
||
# 'default': {'color': 'blue'},
|
||
# 'info': {'color': 'blue', 'bold': False},
|
||
# 'loading': {'color': 'orange', 'bold': False},
|
||
# 'warning': {'color': 'orange', 'bold': False},
|
||
# 'error': {'color': 'red', 'bold': True},
|
||
# 'trigger': {'color': 'green', 'bold': False},
|
||
# 'debug': {'color': 'gray', 'bold': False},
|
||
# }
|
||
|
||
LOG_STYLES = {
|
||
'default': {'foreground': 'blue'},
|
||
'info': {'foreground': 'blue'},
|
||
'loading': {'foreground': 'orange'},
|
||
'warning': {'foreground': 'orange'},
|
||
'error': {'foreground': 'red'},
|
||
'trigger': {'foreground': 'green'},
|
||
'debug': {'foreground': 'gray'},
|
||
}
|
||
|
||
class Logger:
|
||
def __init__(self):
|
||
self.log_queue = queue.Queue()
|
||
self.append_log_func = None # 主程序的日志回调函数
|
||
|
||
def set_append_log(self, func):
|
||
"""设置主程序中的 append_log 函数"""
|
||
self.append_log_func = func
|
||
|
||
def log(self, message, level='default'):
|
||
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||
full_message = f"[{timestamp}] {message}"
|
||
|
||
# 控制台带颜色输出
|
||
color = LOG_COLORS.get(level.lower(), Fore.WHITE)
|
||
print(f"{color}{full_message}{Style.RESET_ALL}")
|
||
|
||
# 触发UI更新(如果已注册)
|
||
if self.append_log_func:
|
||
log_type = level
|
||
self.append_log_func(full_message, log_type)
|
||
|
||
def info(self, message): self.log(message, 'info')
|
||
def warning(self, message): self.log(message, 'warning')
|
||
def error(self, message): self.log(message, 'error')
|
||
def trigger(self, message): self.log(message, 'trigger')
|
||
def debug(self, message): self.log(message, 'debug')
|
||
|
||
|
||
# 全局日志实例
|
||
global_logger = Logger()
|
||
|
||
# 便捷方法,方便其他模块直接使用
|
||
def setup_logger(append_log_func):
|
||
global_logger.set_append_log(append_log_func)
|
||
|
||
def log_info(msg): global_logger.info(msg)
|
||
def log_warning(msg): global_logger.warning(msg)
|
||
def log_error(msg): global_logger.error(msg)
|
||
def log_trigger(msg): global_logger.trigger(msg)
|
||
def log_debug(msg): global_logger.debug(msg)
|