format一遍+logger颜色继续改

This commit is contained in:
shenjack 2022-09-04 13:53:09 +08:00
parent fc734a62cb
commit af96529f76
22 changed files with 125 additions and 123 deletions

View File

@ -16,4 +16,3 @@ from .delivery import Delivery
# lazy之后之前全部导入的(太多了写不动__all__了 # lazy之后之前全部导入的(太多了写不动__all__了
from .scientific_unit import * from .scientific_unit import *

View File

@ -1,4 +1,3 @@
# ------------------------------- # -------------------------------
# Difficult Rocket # Difficult Rocket
# Copyright © 2021-2022 by shenjackyuanjie 3695888@qq.com # Copyright © 2021-2022 by shenjackyuanjie 3695888@qq.com

View File

@ -10,4 +10,3 @@ mail: 3695888@qq.com
github: @shenjackyuanjie github: @shenjackyuanjie
gitee: @shenjackyuanjie gitee: @shenjackyuanjie
""" """

View File

@ -31,5 +31,3 @@ class DRScreen(BaseScreen):
class DRDEBUGScreen(BaseScreen): class DRDEBUGScreen(BaseScreen):
def __init__(self, main_window: ClientWindow): def __init__(self, main_window: ClientWindow):
super().__init__(main_window) super().__init__(main_window)

View File

@ -28,5 +28,3 @@ class BaseRuntimeError(RuntimeError):
class TestError(BaseRuntimeError): class TestError(BaseRuntimeError):
"""在 test 啦""" """在 test 啦"""

View File

@ -61,4 +61,3 @@ class CommandQMarkSufMissing(CommandQMarkMissing):
"""命令中 后面的引号缺失(引号未闭合) """命令中 后面的引号缺失(引号未闭合)
例如: /command "aaaawaa some command""" 例如: /command "aaaawaa some command"""
pre_qmark_pos = None pre_qmark_pos = None

View File

@ -6,7 +6,6 @@
from Difficult_Rocket.exception import BaseError, BaseRuntimeError from Difficult_Rocket.exception import BaseError, BaseRuntimeError
__all__ = ['LanguageNotFound', __all__ = ['LanguageNotFound',
'TranslateError', 'TranslateError',
'TranslateKeyNotFound', 'TranslateKeyNotFound',
@ -27,4 +26,3 @@ class TranslateKeyNotFound(TranslateError):
class TranslateFileNotFound(TranslateError): class TranslateFileNotFound(TranslateError):
"""翻译文件缺失""" """翻译文件缺失"""

View File

@ -1,4 +1,3 @@
# ------------------------------- # -------------------------------
# Difficult Rocket # Difficult Rocket
# Copyright © 2021-2022 by shenjackyuanjie 3695888@qq.com # Copyright © 2021-2022 by shenjackyuanjie 3695888@qq.com

View File

@ -10,4 +10,3 @@ mail: 3695888@qq.com
github: @shenjackyuanjie github: @shenjackyuanjie
gitee: @shenjackyuanjie gitee: @shenjackyuanjie
""" """

View File

@ -4,6 +4,7 @@
# All rights reserved # All rights reserved
# ------------------------------- # -------------------------------
from colorama import Fore, Back, Style from colorama import Fore, Back, Style
print(Fore.RED + 'some red text') print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background') print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text') print(Style.DIM + 'and in dim text')

View File

@ -1,4 +1,3 @@
import os import os
# include 目录 # include 目录
@ -38,4 +37,3 @@ compile_command = "gcc.exe ./py_cprint.c {}{}".format(include_command, compile_o
print(compile_command) print(compile_command)
os.system(compile_command) os.system(compile_command)

View File

@ -1,4 +1,3 @@
from objprint import objprint from objprint import objprint
from ctypes import cdll from ctypes import cdll
@ -6,4 +5,3 @@ from ctypes import cdll
cprint = cdll.LoadLibrary("./cprint.dll") cprint = cdll.LoadLibrary("./cprint.dll")
# objprint(cprint) # objprint(cprint)

View File

@ -14,4 +14,3 @@ pycprint.print("abcdefg\n")
pycprint.printf('aaaa') pycprint.printf('aaaa')
pycprint.printf("啊啊啊abc啊怎么了") pycprint.printf("啊啊啊abc啊怎么了")

View File

@ -6,4 +6,5 @@
def print(text: str) -> None: ... # 直接调用fprint def print(text: str) -> None: ... # 直接调用fprint
def printf(text: str) -> None: ... # 测试中 def printf(text: str) -> None: ... # 测试中

View File

@ -14,6 +14,7 @@ from logging import NOTSET, DEBUG, INFO, WARNING, ERROR, FATAL
from types import FrameType from types import FrameType
from typing import Optional, Union, Dict, Iterable, Tuple, Any from typing import Optional, Union, Dict, Iterable, Tuple, Any
os.system('')
# print(os.path.abspath(os.curdir)) # print(os.path.abspath(os.curdir))
# 如果想要直接使用 logger 来 logging # 如果想要直接使用 logger 来 logging
@ -87,7 +88,7 @@ logger_configs = {
}, },
'server': { 'server': {
'level': TRACE, 'level': TRACE,
'color': 'main_color', 'color': 'DiGua_color',
'file': 'main_log_file', 'file': 'main_log_file',
}, },
}, },
@ -98,7 +99,7 @@ logger_configs = {
'file_name': '\033[38;2;0;255;180m', 'file_name': '\033[38;2;0;255;180m',
'code_line': '\033[38;2;0;255;180m', 'code_line': '\033[38;2;0;255;180m',
'logger': '\033[0m', 'logger': '\033[0m',
TRACE: {'info': '\033[38;2;138;173;244m', 'message': '\033[38;2;40;40;70m'}, 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'}, 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'}, DEBUG: {'info': '\033[38;2;133;138;149m', 'message': '\033[38;2;133;138;149m'},
INFO: {'info': '\033[0m', 'message': '\033[0m'}, INFO: {'info': '\033[0m', 'message': '\033[0m'},
@ -107,18 +108,19 @@ logger_configs = {
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'} 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': { 'DiGua_color': {
'file_time': '\033[38;2;201;222;56m', # catppuccin Macchiato
'main_time': '\033[38;2;201;222;56m', 'file_time': '\033[38;2;238;212;159m',
'file_name': '\033[38;2;0;255;180m', 'main_time': '\033[38;2;202;211;245m',
'code_line': '\033[38;2;0;255;180m', 'file_name': '\033[38;2;139;213;202m',
'code_line': '\033[38;2;166;218;149m',
'logger': '\033[0m', 'logger': '\033[0m',
TRACE: {'info': '\033[34;48;2;44;44;54m', 'message': '\033[34;48;2;40;40;70m'}, TRACE: {'info': '\033[38;2;138;173;244m', 'message': '\033[38;2;138;173;244m'},
FINE: {'info': '\033[35;48;2;44;44;54m', 'message': '\033[35m'}, 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'}, DEBUG: {'info': '\033[38;2;133;138;149m', 'message': '\033[38;2;133;138;149m'},
INFO: {'info': '\033[0m', 'message': '\033[0m'}, INFO: {'info': '\033[0m', 'message': '\033[0m'},
WARNING: {'info': '\033[33m', 'message': '\033[33m'}, WARNING: {'info': '\033[38;2;245;169;127m', 'message': '\033[38;2;245;169;127m'},
ERROR: {'info': '\033[31m', 'message': '\033[31m'}, 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'} 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': {
@ -274,7 +276,6 @@ class LogFileCache:
def _log_file_time_write(self, thread: bool = False) -> None: def _log_file_time_write(self, thread: bool = False) -> None:
"""使用 threading.Timer 调用的定时写入日志文件的函数""" """使用 threading.Timer 调用的定时写入日志文件的函数"""
print(f'write! {thread}{self.log_cache.cache}')
if self.log_cache: if self.log_cache:
with self.time_limit_lock: with self.time_limit_lock:
if self.log_cache: if self.log_cache:
@ -320,7 +321,6 @@ class Logger:
self.level = level if level is not None else DEBUG self.level = level if level is not None else DEBUG
self.colors = colors or logger_configs['Color']['main_color'] self.colors = colors or logger_configs['Color']['main_color']
self.formats = formats or logger_configs['Formatter'].copy() self.formats = formats or logger_configs['Formatter'].copy()
self.formats['logger_name'] = f'{self.colors["logger"]}{self.name}{color_reset_suffix}'
if file_conf: if file_conf:
self.file_cache = LogFileCache(file_conf=file_conf) self.file_cache = LogFileCache(file_conf=file_conf)
else: else:
@ -360,14 +360,15 @@ class Logger:
level_with_color = f"{level_with_color}{' ' * (9 - len_without_color_maker(level_with_color))}" level_with_color = f"{level_with_color}{' ' * (9 - len_without_color_maker(level_with_color))}"
formats = self.formats.copy() formats = self.formats.copy()
if frame is not None: 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['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['code_line']}{frame.f_lineno}{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()) now_time = str(time.time())
for key, value in formats.items(): for key, value in formats.items():
if isinstance(value, dict): if isinstance(value, dict):
if 'strftime' in value: if 'strftime' in value:
value['strftime']: str 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, print_text = self.formats['MESSAGE']['format'].format(level_with_color=level_with_color,
level=level_with_color, message=text, level=level_with_color, message=text,
**formats) **formats)
@ -422,6 +423,8 @@ class Logger:
def get_key_from_dict(a_dict: Dict, key: Any, default: Any = None) -> Optional[Any]: def get_key_from_dict(a_dict: Dict, key: Any, default: Any = None) -> Optional[Any]:
if default is None:
return a_dict[key]
try: try:
return a_dict[key] return a_dict[key]
except KeyError: except KeyError:
@ -473,7 +476,7 @@ def gen_file_conf(file_name: str,
'cache_time': file_cache_time} '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 = logger_configs['Color']['main_color'].copy()
default_color.update(colors) default_color.update(colors)
return default_color return default_color
@ -518,7 +521,21 @@ def get_logger(name: str = 'root') -> Logger:
level=the_config['level'], level=the_config['level'],
file_conf=logger_configs['File'][the_config['file']] if 'file' in the_config else None, 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')], 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): def test_logger(the_logger: Logger):
@ -533,9 +550,11 @@ def test_logger(the_logger: Logger):
if __name__ == "__main__": if __name__ == "__main__":
os.chdir('D:/githubs/DR') os.chdir('D:/githubs/DR')
logger = Logger(name="Main", level=NOTSET) logger = get_logger('server')
logger.info('my name is:', logger.name) logger.info('my name is:', logger.name)
a_logger = get_logger('client') a_logger = get_logger('client')
a_logger.trace('tracing') a_logger.trace('tracing')
time.sleep(1.1) time.sleep(1.1)
a_logger.fine('some fine!') a_logger.fine('some fine!')

View File

@ -20,7 +20,6 @@ from Difficult_Rocket import DR_runtime, DR_option
from Difficult_Rocket.utils import tools from Difficult_Rocket.utils import tools
from Difficult_Rocket.exception.language import * from Difficult_Rocket.exception.language import *
""" """
这部分代码使用了中文编程why 这部分代码使用了中文编程why
你觉得呢 你觉得呢
@ -32,6 +31,7 @@ class Tr:
我不装了我就抄了tr 我不装了我就抄了tr
GOOD GOOD
""" """
def __init__(self): def __init__(self):
self.config_regs = {} self.config_regs = {}
@ -47,8 +47,6 @@ class Tr:
... ...
class Lang: class Lang:
""" """
用于创建一个对应语言的翻译类 用于创建一个对应语言的翻译类