️ 提升了使用fmt时的性能,优化了算法

This commit is contained in:
Nanaloveyuki
2025-07-28 17:06:05 +08:00
parent 827658beab
commit 563cecac97
6 changed files with 48 additions and 59 deletions

View File

@ -7,11 +7,11 @@
"enable_console": true,
"enable_file": true,
"console_color": true,
"console_level": "INFO",
"console_level": "DEBUG",
"console_format": "{time} {levelname} | {prefix}{message}",
"console_prefix": "Auto",
"console_encoding": "utf-8",
"date_format": "%Y-%m-%d %H:%M:%S",
"asctime_format": "%Y-%m-%d %H:%M:%S",
"level_name": {
"DEBUG": "DEBUG",
"INFO": "INFO",

View File

@ -5,7 +5,10 @@ py-logiliteal's config settings, used to set py-logiliteal's global config
# encoding = utf-8
# python 3.13.5
from .utils import get_config, set_config, reset_config, get_asctime, get_date, get_time, get_weekday, fmt_console, fmt_placeholder, fmt_message, fmt_level_name, set_style
from .utils import get_config, set_config, reset_config, create_backup
from .utils import get_asctime, get_date, get_time, get_weekday
from .utils import fmt_console, fmt_placeholder, fmt_message, fmt_level_name
from .utils import set_style, set_color, set_bg_color
from .levels import Logger
__all__ = [
@ -23,5 +26,6 @@ __all__ = [
"set_style",
"set_color",
"set_bg_color",
"create_backup",
"Logger" # 日志记录器非实例化
]

View File

@ -5,7 +5,7 @@ Utility functions
# encoding = utf-8
# python 3.13.5
from .configs import get_config, set_config, reset_config
from .configs import get_config, set_config, reset_config, create_backup
from .time import get_asctime, get_date, get_time, get_weekday
from .fmt import fmt_console, fmt_placeholder, fmt_message, fmt_level_name
from .styles import set_color, set_bg_color, set_style
@ -14,6 +14,7 @@ __all__ = [
"get_config",
"set_config",
"reset_config",
"create_backup",
"get_asctime",
"get_date",
"get_time",
@ -24,5 +25,5 @@ __all__ = [
"fmt_level_name",
"set_color",
"set_bg_color",
"set_style"
"set_style",
]

View File

@ -9,7 +9,6 @@ py-logiliteal's config settings, used to set py-logiliteal's global config
import json
from os import remove
import shutil
import time
from pathlib import Path
from typing import Union, Optional, Tuple
from logging import error
@ -28,7 +27,7 @@ DEFAULT_CONFIG = {
"console_format": "{time} {levelname} | {prefix}{message}",
"console_prefix": "Auto",
"console_encoding": "utf-8",
"date_format": "%Y-%m-%d %H:%M:%S",
"asctime_format": "%Y-%m-%d %H:%M:%S",
"level_name": {"DEBUG": "DEBUG", "INFO": "INFO", "WARN": "WARN", "ERRO": "ERRO", "CRIT": "CRIT"},
"level_color": {"DEBUG": "#c1d5ff", "INFO": "#c1ffff", "WARN": "#fff600", "ERRO": "#ffa000", "CRIT": "#ff8181"},
}

View File

@ -7,7 +7,7 @@ py-logiliteal's formatter, used to format log output
# python 3.13.5
from .configs import get_config
from typing import Any, Optional, Union
from typing import Any, Optional
from .time import get_asctime, get_time, get_weekday, get_date
from .styles import set_color, set_bg_color
import re
@ -20,15 +20,14 @@ def fmt_level(level: str) -> int:
:return: 格式化后的日志级别 Formatted log level
"""
level_map = {
"DEBUG": 10,
"INFO": 20,
"WARN": 30,
"ERRO": 40,
"CRIT": 50,
"DEBUG": 0,
"INFO": 10,
"WARN": 20,
"ERRO": 30,
"CRIT": 40,
"UNKN": 50
}
if level == "UNKN":
return -1
return level_map.get(level.upper(), 0)
return level_map.get(level.upper(), 50)
def fmt_level_number(level: int) -> str:
"""
@ -37,15 +36,15 @@ def fmt_level_number(level: int) -> str:
:param level: 日志级别数字 Log level number
:return: 格式化后的日志级别 Formatted log level
"""
if level <= 10 and level >= 0:
if level < 10:
return "DEBUG"
elif level <= 20 and level > 10:
elif level < 20:
return "INFO"
elif level <= 30 and level > 20:
elif level < 30:
return "WARN"
elif level <= 40 and level > 30:
elif level < 40:
return "ERRO"
elif level <= 50 and level > 40:
elif level < 50:
return "CRIT"
else:
return "UNKN"
@ -88,46 +87,34 @@ def fmt_message(message: Any, no_placeholder: bool = False, no_color: bool = Fal
"""
def process_color_tags(msg: str) -> str:
from io import StringIO
output = StringIO()
stack = []
result = []
current_content = []
last_end = 0
pattern = re.compile(r'(<#([0-9a-fA-F]{6})>|</>)')
current_color = None
for match in pattern.finditer(msg):
text_between = msg[last_end:match.start()]
if stack:
current_content.append(text_between)
else:
result.append(text_between)
last_end = match.end()
output.write(msg[last_end:match.start()])
tag = match.group(1)
last_end = match.end()
if tag.startswith('<#'):
color_code = match.group(2)
stack.append(color_code)
stack.append(current_color)
current_color = match.group(2)
else:
if stack:
color = stack.pop()
colored_content = set_color(''.join(current_content), f'#{color}')
result.append(colored_content)
current_content = []
current_color = stack.pop()
else:
result.append(tag)
output.write(tag)
remaining_text = msg[last_end:]
if stack:
current_content.append(remaining_text)
else:
result.append(remaining_text)
for color in reversed(stack):
result.append(f'<#{color}>')
result.append(''.join(current_content))
current_content = []
return ''.join(result)
output.write(msg[last_end:])
result = output.getvalue()
output.close()
if current_color:
result += ''.join(f'<#{color}>' for color in reversed(stack)) if stack else f'<#{current_color}>'
return result
if no_color:
processed_message = str(message)
else:
@ -161,14 +148,12 @@ def fmt_console(level: int, message: Any, prefix: str | None = None) -> Optional
:param message: 消息内容 Message content
:return: 格式化后的消息 Formatted message
"""
cl = get_config("console_level")
fmt = get_config("console_format")
if fmt_level(cl) > level:
console_level = get_config("console_level")
if level != -1 and fmt_level(console_level) > level:
return None
if prefix is None:
prefix = ""
fmt = fmt_placeholder(fmt)
return fmt.format(
fmt = get_config("console_format")
prefix = prefix or ""
return fmt_placeholder(fmt).format(
levelname = fmt_level_name(fmt_level_number(level)),
prefix = fmt_message(prefix, no_placeholder=True),
message = fmt_message(message, no_placeholder=True)

View File

@ -23,7 +23,7 @@ def get_asctime() -> str:
global cache_asctime
if cache_asctime:
return cache_asctime
cache_asctime = datetime.now().strftime(get_config("date_format"))
cache_asctime = datetime.now().strftime(get_config("asctime_format"))
return cache_asctime
def get_time() -> str: