From af96529f7657aecf3f1c6125a674dc01dbad001c Mon Sep 17 00:00:00 2001 From: shenjack <3695888@qq.com> Date: Sun, 4 Sep 2022 13:53:09 +0800 Subject: [PATCH] =?UTF-8?q?format=E4=B8=80=E9=81=8D+logger=E9=A2=9C?= =?UTF-8?q?=E8=89=B2=E7=BB=A7=E7=BB=AD=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Difficult_Rocket/api/__init__.py | 1 - Difficult_Rocket/api/exception/logger.py | 3 +- Difficult_Rocket/api/exception/main.py | 1 - Difficult_Rocket/api/exception/threading.py | 2 +- Difficult_Rocket/client/guis/format/html.py | 14 +- Difficult_Rocket/client/guis/widgets.py | 16 +-- Difficult_Rocket/client/screen.py | 2 - Difficult_Rocket/command/tree.py | 26 ++-- Difficult_Rocket/crash/crash.py | 2 +- Difficult_Rocket/exception/__init__.py | 2 - Difficult_Rocket/exception/command.py | 1 - Difficult_Rocket/exception/language.py | 2 - Difficult_Rocket/exception/logger.py | 1 - Difficult_Rocket/exception/main.py | 1 - Difficult_Rocket/utils/cprint/colors.py | 3 +- Difficult_Rocket/utils/cprint/compile.py | 8 +- Difficult_Rocket/utils/cprint/dll_load.py | 2 - Difficult_Rocket/utils/cprint/py_cprint.py | 1 - Difficult_Rocket/utils/cprint/pycprint.pyi | 1 + Difficult_Rocket/utils/logger.py | 151 +++++++++++--------- Difficult_Rocket/utils/tools.py | 4 +- Difficult_Rocket/utils/translate.py | 4 +- 22 files changed, 125 insertions(+), 123 deletions(-) diff --git a/Difficult_Rocket/api/__init__.py b/Difficult_Rocket/api/__init__.py index c51b7f0..1df666e 100644 --- a/Difficult_Rocket/api/__init__.py +++ b/Difficult_Rocket/api/__init__.py @@ -16,4 +16,3 @@ from .delivery import Delivery # lazy之后之前全部导入的(太多了写不动__all__了 from .scientific_unit import * - diff --git a/Difficult_Rocket/api/exception/logger.py b/Difficult_Rocket/api/exception/logger.py index 5df3184..7a1357f 100644 --- a/Difficult_Rocket/api/exception/logger.py +++ b/Difficult_Rocket/api/exception/logger.py @@ -1,4 +1,3 @@ - # ------------------------------- # Difficult Rocket # Copyright © 2021-2022 by shenjackyuanjie 3695888@qq.com @@ -9,4 +8,4 @@ from Difficult_Rocket.exception.logger import * __all__ = [ "LogFileLockTimeOutError" -] \ No newline at end of file +] diff --git a/Difficult_Rocket/api/exception/main.py b/Difficult_Rocket/api/exception/main.py index a192dd5..fc7a7cc 100644 --- a/Difficult_Rocket/api/exception/main.py +++ b/Difficult_Rocket/api/exception/main.py @@ -10,4 +10,3 @@ mail: 3695888@qq.com github: @shenjackyuanjie gitee: @shenjackyuanjie """ - diff --git a/Difficult_Rocket/api/exception/threading.py b/Difficult_Rocket/api/exception/threading.py index 95b166e..748d739 100644 --- a/Difficult_Rocket/api/exception/threading.py +++ b/Difficult_Rocket/api/exception/threading.py @@ -8,4 +8,4 @@ from Difficult_Rocket.exception.threading import * __all__ = [ "LockTimeOutError" -] \ No newline at end of file +] diff --git a/Difficult_Rocket/client/guis/format/html.py b/Difficult_Rocket/client/guis/format/html.py index 79fc3dc..8424224 100644 --- a/Difficult_Rocket/client/guis/format/html.py +++ b/Difficult_Rocket/client/guis/format/html.py @@ -18,8 +18,8 @@ from utils import translate default_style = { 'font_name': 'Times New Roman', 'font_size': 12, - 'bold': False, - 'italic': False + 'bold': False, + 'italic': False } @@ -222,7 +222,7 @@ default_fonts_config = [ # Markdown 粗体语法规则匹配 'match': re.compile(r'\*\*(.*?(? None: ... -def create_crash_report(info: str = None) -> None: +def create_crash_report(info: str = None) -> None: crash_info = crash_info_handler(info) if 'crash_report' not in os.listdir('./'): os.mkdir('./crash_report') diff --git a/Difficult_Rocket/exception/__init__.py b/Difficult_Rocket/exception/__init__.py index ad3f24e..d946d73 100644 --- a/Difficult_Rocket/exception/__init__.py +++ b/Difficult_Rocket/exception/__init__.py @@ -28,5 +28,3 @@ class BaseRuntimeError(RuntimeError): class TestError(BaseRuntimeError): """在 test 啦""" - - diff --git a/Difficult_Rocket/exception/command.py b/Difficult_Rocket/exception/command.py index 63325b6..801d756 100644 --- a/Difficult_Rocket/exception/command.py +++ b/Difficult_Rocket/exception/command.py @@ -61,4 +61,3 @@ class CommandQMarkSufMissing(CommandQMarkMissing): """命令中 后面的引号缺失(引号未闭合) 例如: /command "aaaawaa some command""" pre_qmark_pos = None - diff --git a/Difficult_Rocket/exception/language.py b/Difficult_Rocket/exception/language.py index 683c6f9..ec0c083 100644 --- a/Difficult_Rocket/exception/language.py +++ b/Difficult_Rocket/exception/language.py @@ -6,7 +6,6 @@ from Difficult_Rocket.exception import BaseError, BaseRuntimeError - __all__ = ['LanguageNotFound', 'TranslateError', 'TranslateKeyNotFound', @@ -27,4 +26,3 @@ class TranslateKeyNotFound(TranslateError): class TranslateFileNotFound(TranslateError): """翻译文件缺失""" - diff --git a/Difficult_Rocket/exception/logger.py b/Difficult_Rocket/exception/logger.py index 2109f67..dfd2dcd 100644 --- a/Difficult_Rocket/exception/logger.py +++ b/Difficult_Rocket/exception/logger.py @@ -1,4 +1,3 @@ - # ------------------------------- # Difficult Rocket # Copyright © 2021-2022 by shenjackyuanjie 3695888@qq.com diff --git a/Difficult_Rocket/exception/main.py b/Difficult_Rocket/exception/main.py index a192dd5..fc7a7cc 100644 --- a/Difficult_Rocket/exception/main.py +++ b/Difficult_Rocket/exception/main.py @@ -10,4 +10,3 @@ mail: 3695888@qq.com github: @shenjackyuanjie gitee: @shenjackyuanjie """ - diff --git a/Difficult_Rocket/utils/cprint/colors.py b/Difficult_Rocket/utils/cprint/colors.py index 1d95fea..65a0770 100644 --- a/Difficult_Rocket/utils/cprint/colors.py +++ b/Difficult_Rocket/utils/cprint/colors.py @@ -4,8 +4,9 @@ # All rights reserved # ------------------------------- from colorama import Fore, Back, Style + print(Fore.RED + 'some red text') print(Back.GREEN + 'and with a green background') print(Style.DIM + 'and in dim text') print(Style.RESET_ALL) -print('back to normal now') \ No newline at end of file +print('back to normal now') diff --git a/Difficult_Rocket/utils/cprint/compile.py b/Difficult_Rocket/utils/cprint/compile.py index dad5791..21ba8f8 100644 --- a/Difficult_Rocket/utils/cprint/compile.py +++ b/Difficult_Rocket/utils/cprint/compile.py @@ -1,4 +1,3 @@ - import os # include 目录 @@ -7,10 +6,10 @@ include_paths = ["C:\\Users\\shenjack.SHENJACK-5600X\\AppData\\Local\\Programs\\ # 编译选项 compile_options = { "-shared": None, - "-O3": None, - "-Wall": None, + "-O3": None, + "-Wall": None, "-Werror": None, - "-o": "./py_cprint.dll" + "-o": "./py_cprint.dll" } include_command = "-I " @@ -38,4 +37,3 @@ compile_command = "gcc.exe ./py_cprint.c {}{}".format(include_command, compile_o print(compile_command) os.system(compile_command) - diff --git a/Difficult_Rocket/utils/cprint/dll_load.py b/Difficult_Rocket/utils/cprint/dll_load.py index f61baed..fe5358e 100644 --- a/Difficult_Rocket/utils/cprint/dll_load.py +++ b/Difficult_Rocket/utils/cprint/dll_load.py @@ -1,4 +1,3 @@ - from objprint import objprint from ctypes import cdll @@ -6,4 +5,3 @@ from ctypes import cdll cprint = cdll.LoadLibrary("./cprint.dll") # objprint(cprint) - diff --git a/Difficult_Rocket/utils/cprint/py_cprint.py b/Difficult_Rocket/utils/cprint/py_cprint.py index adb1efa..233c098 100644 --- a/Difficult_Rocket/utils/cprint/py_cprint.py +++ b/Difficult_Rocket/utils/cprint/py_cprint.py @@ -14,4 +14,3 @@ pycprint.print("abcdefg\n") pycprint.printf('aaaa') pycprint.printf("啊啊啊abc啊,怎么了") - diff --git a/Difficult_Rocket/utils/cprint/pycprint.pyi b/Difficult_Rocket/utils/cprint/pycprint.pyi index fcd3c83..6300e6f 100644 --- a/Difficult_Rocket/utils/cprint/pycprint.pyi +++ b/Difficult_Rocket/utils/cprint/pycprint.pyi @@ -6,4 +6,5 @@ def print(text: str) -> None: ... # 直接调用fprint + def printf(text: str) -> None: ... # 测试中 diff --git a/Difficult_Rocket/utils/logger.py b/Difficult_Rocket/utils/logger.py index 29f6c8f..5262fa9 100644 --- a/Difficult_Rocket/utils/logger.py +++ b/Difficult_Rocket/utils/logger.py @@ -14,6 +14,7 @@ from logging import NOTSET, DEBUG, INFO, WARNING, ERROR, FATAL from types import FrameType from typing import Optional, Union, Dict, Iterable, Tuple, Any +os.system('') # print(os.path.abspath(os.curdir)) # 如果想要直接使用 logger 来 logging @@ -49,97 +50,98 @@ TRACE = 5 FINE = 7 level_name_map = { - ALL: 'ALL', # NOTSET - TRACE: 'TRACE', - FINE: 'FINE', - DEBUG: 'DEBUG', - INFO: 'INFO', + ALL: 'ALL', # NOTSET + TRACE: 'TRACE', + FINE: 'FINE', + DEBUG: 'DEBUG', + INFO: 'INFO', WARNING: 'WARNING', # WARN - ERROR: 'ERROR', - FATAL: 'FATAL' + ERROR: 'ERROR', + FATAL: 'FATAL' } name_level_map = { - 'NOTSET': ALL, - 'ALL': ALL, - 'TRACE': TRACE, - 'FINE': FINE, - 'DEBUG': DEBUG, - 'INFO': INFO, - 'WARNING': WARNING, - 'WARN': WARNING, - 'ERROR': ERROR, + 'NOTSET': ALL, + 'ALL': ALL, + 'TRACE': TRACE, + 'FINE': FINE, + 'DEBUG': DEBUG, + 'INFO': INFO, + 'WARNING': WARNING, + 'WARN': WARNING, + 'ERROR': ERROR, 'CRITICAL': FATAL, - 'FATAL': FATAL + 'FATAL': FATAL } logger_configs = { - 'Logger': { - 'root': { + 'Logger': { + 'root': { 'level': TRACE, 'color': 'main_color', - 'file': 'main_log_file', + 'file': 'main_log_file', }, 'client': { 'level': TRACE, 'color': 'main_color', - 'file': 'main_log_file', + 'file': 'main_log_file', }, 'server': { 'level': TRACE, - 'color': 'main_color', - 'file': 'main_log_file', + 'color': 'DiGua_color', + 'file': 'main_log_file', }, }, - 'Color': { - 'main_color': { + 'Color': { + 'main_color': { 'file_time': '\033[38;2;201;222;56m', 'main_time': '\033[38;2;201;222;56m', 'file_name': '\033[38;2;0;255;180m', 'code_line': '\033[38;2;0;255;180m', - 'logger': '\033[0m', - TRACE: {'info': '\033[38;2;138;173;244m', 'message': '\033[38;2;40;40;70m'}, - FINE: {'info': '\033[35;48;2;44;44;54m', 'message': '\033[35m'}, - DEBUG: {'info': '\033[38;2;133;138;149m', 'message': '\033[38;2;133;138;149m'}, - INFO: {'info': '\033[0m', 'message': '\033[0m'}, - WARNING: {'info': '\033[33m', 'message': '\033[33m'}, - ERROR: {'info': '\033[31m', 'message': '\033[31m'}, - FATAL: {'info': '\033[38;2;255;255;0;48;2;120;10;10m', 'message': '\033[38;2;255;255;0;48;2;120;10;10m'} + 'logger': '\033[0m', + TRACE: {'info': '\033[38;2;138;173;244m', 'message': '\033[38;2;40;40;200m'}, + FINE: {'info': '\033[35;48;2;44;44;54m', 'message': '\033[35m'}, + DEBUG: {'info': '\033[38;2;133;138;149m', 'message': '\033[38;2;133;138;149m'}, + INFO: {'info': '\033[0m', 'message': '\033[0m'}, + WARNING: {'info': '\033[33m', 'message': '\033[33m'}, + ERROR: {'info': '\033[31m', 'message': '\033[31m'}, + FATAL: {'info': '\033[38;2;255;255;0;48;2;120;10;10m', 'message': '\033[38;2;255;255;0;48;2;120;10;10m'} }, 'DiGua_color': { - 'file_time': '\033[38;2;201;222;56m', - 'main_time': '\033[38;2;201;222;56m', - 'file_name': '\033[38;2;0;255;180m', - 'code_line': '\033[38;2;0;255;180m', - 'logger': '\033[0m', - TRACE: {'info': '\033[34;48;2;44;44;54m', 'message': '\033[34;48;2;40;40;70m'}, - FINE: {'info': '\033[35;48;2;44;44;54m', 'message': '\033[35m'}, - DEBUG: {'info': '\033[38;2;133;138;149m', 'message': '\033[38;2;133;138;149m'}, - INFO: {'info': '\033[0m', 'message': '\033[0m'}, - WARNING: {'info': '\033[33m', 'message': '\033[33m'}, - ERROR: {'info': '\033[31m', 'message': '\033[31m'}, - FATAL: {'info': '\033[38;2;255;255;0;48;2;120;10;10m', 'message': '\033[38;2;255;255;0;48;2;120;10;10m'} + # catppuccin Macchiato + 'file_time': '\033[38;2;238;212;159m', + 'main_time': '\033[38;2;202;211;245m', + 'file_name': '\033[38;2;139;213;202m', + 'code_line': '\033[38;2;166;218;149m', + 'logger': '\033[0m', + TRACE: {'info': '\033[38;2;138;173;244m', 'message': '\033[38;2;138;173;244m'}, + FINE: {'info': '\033[38;2;198;160;246m', 'message': '\033[38;2;198;160;246m'}, + DEBUG: {'info': '\033[38;2;133;138;149m', 'message': '\033[38;2;133;138;149m'}, + INFO: {'info': '\033[0m', 'message': '\033[0m'}, + WARNING: {'info': '\033[38;2;245;169;127m', 'message': '\033[38;2;245;169;127m'}, + ERROR: {'info': '\033[38;2;237;135;150m', 'message': '\033[38;2;237;135;150m'}, + FATAL: {'info': '\033[38;2;255;255;0;48;2;120;10;10m', 'message': '\033[38;2;255;255;0;48;2;120;10;10m', 'logger': '\033[38;2;245;189;230m'} } }, - 'File': { + 'File': { 'main_log_file': { - 'mode': 'a', - 'encoding': 'utf-8', - 'level': TRACE, - 'file_name': './logs/{file_time}_logs.md', - 'cache_len': 10, + 'mode': 'a', + 'encoding': 'utf-8', + 'level': TRACE, + 'file_name': './logs/{file_time}_logs.md', + 'cache_len': 10, 'cache_time': 1 }, }, 'Formatter': { - 'MESSAGE': { + 'MESSAGE': { 'format': '[{main_time}] [{logger_name}] {level} | {file_name}:{code_line} | {message}' }, 'file_name': 'no frame', 'code_line': 'no frame', 'file_time': {'strftime': '%Y-%m-%d %H-%M'}, 'main_time': {'strftime': '%Y-%m-%d %H-%M-%S:%%S'}, # %%S 三位毫秒 - ...: ... + ...: ... } } @@ -274,7 +276,6 @@ class LogFileCache: def _log_file_time_write(self, thread: bool = False) -> None: """使用 threading.Timer 调用的定时写入日志文件的函数""" - print(f'write! {thread}{self.log_cache.cache}') if self.log_cache: with self.time_limit_lock: if self.log_cache: @@ -320,7 +321,6 @@ class Logger: self.level = level if level is not None else DEBUG self.colors = colors or logger_configs['Color']['main_color'] self.formats = formats or logger_configs['Formatter'].copy() - self.formats['logger_name'] = f'{self.colors["logger"]}{self.name}{color_reset_suffix}' if file_conf: self.file_cache = LogFileCache(file_conf=file_conf) else: @@ -360,14 +360,15 @@ class Logger: level_with_color = f"{level_with_color}{' ' * (9 - len_without_color_maker(level_with_color))}" formats = self.formats.copy() if frame is not None: - formats['file_name'] = f"{self.colors['file_name']}{os.path.split(frame.f_code.co_filename)[-1]}{color_reset_suffix}" - formats['code_line'] = f"{self.colors['code_line']}{frame.f_lineno}{color_reset_suffix}" + formats['file_name'] = f"{self.colors[level]['file_name']}{os.path.split(frame.f_code.co_filename)[-1]}{color_reset_suffix}" + formats['code_line'] = f"{self.colors[level]['code_line']}{frame.f_lineno}{color_reset_suffix}" + formats['logger_name'] = f'{self.colors[level]["logger"]}{self.name}{color_reset_suffix}' now_time = str(time.time()) for key, value in formats.items(): if isinstance(value, dict): if 'strftime' in value: value['strftime']: str - formats[key] = f"{self.colors[key]}{strftime(value['strftime'].replace('%%S', now_time[now_time.find('.') + 1:now_time.find('.') + 4]))}{color_reset_suffix}" + formats[key] = f"{self.colors[level][key]}{strftime(value['strftime'].replace('%%S', now_time[now_time.find('.') + 1:now_time.find('.') + 4]))}{color_reset_suffix}" print_text = self.formats['MESSAGE']['format'].format(level_with_color=level_with_color, level=level_with_color, message=text, **formats) @@ -422,6 +423,8 @@ class Logger: def get_key_from_dict(a_dict: Dict, key: Any, default: Any = None) -> Optional[Any]: + if default is None: + return a_dict[key] try: return a_dict[key] except KeyError: @@ -465,15 +468,15 @@ def gen_file_conf(file_name: str, file_encoding: str = 'utf-8', file_cache_len: int = 10, file_cache_time: Union[int, float] = 1) -> dict: - return {'file_name': file_name, - 'level': file_level, - 'mode': file_mode, - 'encoding': file_encoding, - 'cache_len': file_cache_len, + return {'file_name': file_name, + 'level': file_level, + 'mode': file_mode, + 'encoding': file_encoding, + 'cache_len': file_cache_len, 'cache_time': file_cache_time} -def gen_color_conf(**colors) -> dict: +def gen_color_conf(color_name: str = None, **colors) -> dict: default_color = logger_configs['Color']['main_color'].copy() default_color.update(colors) return default_color @@ -518,7 +521,21 @@ def get_logger(name: str = 'root') -> Logger: level=the_config['level'], file_conf=logger_configs['File'][the_config['file']] if 'file' in the_config else None, colors=logger_configs['Color'][get_key_from_dict(the_config, 'color', 'main_color')], - formats=logger_configs['Formatter']) + formats=logger_configs['Formatter'].copy()) + + +def format_colors(colors: dict) -> None: + for key, value in colors.items(): + if not isinstance(key, str): + continue + for level, value_ in colors.items(): + if not isinstance(level, int): + continue + colors[level][key] = get_key_from_dict(colors[level], key, colors[key]) + + +for color in logger_configs['Color']: + format_colors(logger_configs['Color'][color]) def test_logger(the_logger: Logger): @@ -533,9 +550,11 @@ def test_logger(the_logger: Logger): if __name__ == "__main__": os.chdir('D:/githubs/DR') - logger = Logger(name="Main", level=NOTSET) + logger = get_logger('server') + logger.info('my name is:', logger.name) a_logger = get_logger('client') + a_logger.trace('tracing') time.sleep(1.1) a_logger.fine('some fine!') diff --git a/Difficult_Rocket/utils/tools.py b/Difficult_Rocket/utils/tools.py index bfc87ad..ab30129 100644 --- a/Difficult_Rocket/utils/tools.py +++ b/Difficult_Rocket/utils/tools.py @@ -32,8 +32,8 @@ file configs """ file_error = {FileNotFoundError: 'no {filetype} file was founded!:\n file name: {filename}\n file_type: {filetype}\n stack: {stack}', - KeyError: 'no stack in {filetype} file {filename} was found! \n file type: {} \n file name: {} \n stack: {stack}', - Exception: 'get some {error_type} error when read {filetype} file {filename}! \n file type: {} \n file name: {} \n stack: {stack}'} + KeyError: 'no stack in {filetype} file {filename} was found! \n file type: {} \n file name: {} \n stack: {stack}', + Exception: 'get some {error_type} error when read {filetype} file {filename}! \n file type: {} \n file name: {} \n stack: {stack}'} def load_file(file_name: str, stack: Union[str, list, dict] = None, raise_error: bool = True) -> Union[dict, list]: diff --git a/Difficult_Rocket/utils/translate.py b/Difficult_Rocket/utils/translate.py index 1b57aac..da5f82f 100644 --- a/Difficult_Rocket/utils/translate.py +++ b/Difficult_Rocket/utils/translate.py @@ -20,7 +20,6 @@ from Difficult_Rocket import DR_runtime, DR_option from Difficult_Rocket.utils import tools from Difficult_Rocket.exception.language import * - """ 这部分代码使用了中文编程,why? 你觉得呢? @@ -32,6 +31,7 @@ class Tr: 我不装了,我就抄了tr GOOD """ + def __init__(self): self.config_regs = {} @@ -47,8 +47,6 @@ class Tr: ... - - class Lang: """ 用于创建一个对应语言的翻译类