import os import threading import time import traceback from queue import Queue from AcrossPlatform.get_platform import GLOBAL_DIR LOG_DIR = os.path.join(GLOBAL_DIR, "Log") os.makedirs(LOG_DIR, exist_ok=True) class LogRecorder: log_queue = Queue() log_initial = threading.Event() log_initial.clear() def __init__(self) -> None: super().__init__() if not LogRecorder.log_initial.is_set(): threading.Thread(target=LogRecorder.log_typer, daemon=True).start() @staticmethod def log_typer(): while True: try: data = LogRecorder.log_queue.get() if data: _time, log_mes, need_print = data real_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(_time)) file_tag = time.strftime("%Y_%m_%d_%H", time.localtime(_time)) file_name = f"{file_tag}.txt" file_path = os.path.join(f"{LOG_DIR}", file_name) with open(file_path, "a") as _file: file = _file mes = f"[{real_time}]{log_mes}\n" if need_print: print(f"\033[93m[{real_time}]{log_mes}\033[0m") file.write(mes) except Exception as e: print(f"[LogRecord Error]:{e.args}\n{traceback.format_exc()}") @staticmethod def write(log_mes, need_print=False): _time = time.time() pkg = [_time, log_mes, need_print] LogRecorder.log_queue.put(pkg) GLOBAL_LOG = LogRecorder()