🐛 修复一些细节小问题

This commit is contained in:
远野千束 2024-10-20 20:59:30 +08:00
parent ef5866343d
commit 13b95c2732
14 changed files with 148 additions and 124 deletions

View File

View File

@ -75,11 +75,6 @@ class Channel(Generic[T]):
if name in _channel: if name in _channel:
raise ValueError(f"Channel {name} already exists") raise ValueError(f"Channel {name} already exists")
_channel[name] = self _channel[name] = self
logger.debug(f"Channel {name} initialized in main process")
else:
logger.debug(
f"Channel {name} initialized in sub process, should manually set in main process"
)
def _get_generic_type(self) -> Optional[type]: def _get_generic_type(self) -> Optional[type]:
""" """

View File

@ -118,6 +118,8 @@ def load_config_in_default(no_waring: bool = False) -> dict[str, Any]:
从一个标准的轻雪项目加载配置文件 从一个标准的轻雪项目加载配置文件
项目目录下的config.*和config目录下的所有配置文件 项目目录下的config.*和config目录下的所有配置文件
项目目录下的配置文件优先 项目目录下的配置文件优先
Args:
no_waring: 是否关闭警告
""" """
config = load_configs_from_dirs("config", no_waring=no_waring) config = load_configs_from_dirs("config", no_waring=no_waring)
config.update( config.update(

View File

@ -12,26 +12,34 @@ import sys
import loguru import loguru
logger = loguru.logger logger = loguru.logger.bind()
# DEBUG日志格式
debug_format: str = ( debug_format: str = (
"<c>{time:YYYY-MM-DD HH:mm:ss}</c> " "<c>{time:YYYY-MM-DD HH:mm:ss}</c> "
"<lvl>[{level.icon}]</lvl> " "<lvl>[{level.icon}{level}]</lvl> "
"<c><{name}.{module}.{function}:{line}></c> " "<c><{name}.{module}.{function}:{line}></c> "
"{message}" "{message}"
) )
# 默认日志格式 # 默认日志格式
default_format: str = ( default_format: str = (
"<c>{time:MM-DD HH:mm:ss}</c> " "<c>{time:MM-DD HH:mm:ss}</c> "
"<lvl>[{level.icon}]</lvl> " "<lvl>[{level.icon}{level}]</lvl> "
"<c><{name}></c> " "<c><{name}></c> "
"{message}" "{message}"
) )
def get_format(level: str) -> str: def get_format(level: str) -> str:
"""
获取日志格式
Args:
level: 日志等级
Returns: 日志格式
"""
# DEBUG日志格式
if level == "DEBUG": if level == "DEBUG":
return debug_format return debug_format
else: else:
@ -41,23 +49,28 @@ def get_format(level: str) -> str:
def init_log(config: dict): def init_log(config: dict):
""" """
在语言加载完成后执行 在语言加载完成后执行
Returns: Args:
config: 配置
""" """
global logger
level = config.get("log_level", "DEBUG")
print("初始化日志系统", level)
logger.remove() logger.remove()
logger.add( logger.add(
sys.stdout, sys.stdout,
level=0, level=level,
diagnose=False, diagnose=False,
format=get_format(config.get("log_level", "INFO")), format=get_format(level),
) )
show_icon = config.get("log_icon", True) show_icon = config.get("log_icon", True)
logger.level("DEBUG", color="<blue>", icon=f"{'🐛' if show_icon else ''}DEBUG") logger.level("DEBUG", color="<blue>", icon=f"{'🐛' if show_icon else ''}")
logger.level("INFO", color="<normal>", icon=f"{'' if show_icon else ''}INFO") logger.level("INFO", color="<normal>", icon=f"{'' if show_icon else ''}")
logger.level("SUCCESS", color="<green>", icon=f"{'' if show_icon else ''}SUCCESS") logger.level("SUCCESS", color="<green>", icon=f"{'' if show_icon else ''}")
logger.level("WARNING", color="<yellow>", icon=f"{'⚠️' if show_icon else ''}WARNING") logger.level("WARNING", color="<yellow>", icon=f"{'⚠️' if show_icon else ''}")
logger.level("ERROR", color="<red>", icon=f"{'' if show_icon else ''}ERROR") logger.level("ERROR", color="<red>", icon=f"{'' if show_icon else ''}")
logger.level("CRITICAL", color="<red>", icon=f"{'' if show_icon else ''}")
logger.level("TRACE", color="<cyan>", icon=f"{'🔍' if show_icon else ''}")
logger.bind()
init_log(config={}) init_log(config={"log_level": "DEBUG", "log_icon": True})

View File

@ -7,6 +7,8 @@ from typing import Iterable
from magicoca import Chan, select from magicoca import Chan, select
from liteyuki.log import logger
def message_handler_thread(i_chans: Iterable[Chan[Any]]): def message_handler_thread(i_chans: Iterable[Chan[Any]]):
""" """
@ -15,4 +17,5 @@ def message_handler_thread(i_chans: Iterable[Chan[Any]]):
Returns: Returns:
""" """
for msg in select(*i_chans): for msg in select(*i_chans):
print("Recv from anybot", msg) logger.debug(f"Recv from anybot {msg}")
logger.info(f"Recv from anybot {msg}")

View File

@ -7,9 +7,10 @@ httpx>=0.27.0
nonebot-plugin-htmlrender>=0.1.0 nonebot-plugin-htmlrender>=0.1.0
nonebot2[fastapi,httpx,websockets]>=2.3.3 nonebot2[fastapi,httpx,websockets]>=2.3.3
nonebot-adapter-onebot>=2.4.3 nonebot-adapter-onebot>=2.4.3
nonebot-plugin-alconna>=0.46.3 nonebot-plugin-alconna>=0.53.0
nonebot_plugin_apscheduler>=0.4.0 nonebot_plugin_apscheduler>=0.4.0
nonebot-adapter-satori>=0.11.5 nonebot-adapter-satori>=0.11.5
mysql-connector-python>=9.1.0
pyppeteer>=2.0.0 pyppeteer>=2.0.0
markdown>=3.3.6 markdown>=3.3.6
zhDateTime>=1.0.3 zhDateTime>=1.0.3
@ -35,3 +36,4 @@ fastapi~=0.115.0
# liteyuki dependencies # liteyuki dependencies
croterline>=1.0.7 croterline>=1.0.7
magicoca>=1.0.5 magicoca>=1.0.5
mysql-connector-python~=9.1.0

View File

@ -1,7 +1,7 @@
import os.path import os.path
from pathlib import Path from pathlib import Path
import nonebot
from croterline.utils import IsMainProcess from croterline.utils import IsMainProcess
from liteyuki.core import sub_process_manager from liteyuki.core import sub_process_manager
@ -14,9 +14,12 @@ __plugin_meta__ = PluginMetadata(
def nb_run(*args, **kwargs): def nb_run(*args, **kwargs):
import nonebot
nonebot.init(**kwargs) nonebot.init(**kwargs)
from .nb_utils import driver_manager, adapter_manager from .nb_utils import driver_manager, adapter_manager
driver_manager.init(config=kwargs) driver_manager.init(config=kwargs)
adapter_manager.init(kwargs) adapter_manager.init(kwargs)
adapter_manager.register() adapter_manager.register()
@ -26,6 +29,7 @@ def nb_run(*args, **kwargs):
if IsMainProcess: if IsMainProcess:
from .dev_reloader import * from .dev_reloader import *
bot = get_bot() bot = get_bot()
sub_process_manager.add( sub_process_manager.add(

View File

@ -50,7 +50,7 @@ async def start_push_thread():
) )
if MESSAGE in plugin_config.gotify_includes: if MESSAGE in plugin_config.gotify_includes:
@on_message().handle() @on_message(block=False, priority=100).handle()
async def _(event: Event): async def _(event: Event):
ctx = Context( ctx = Context(
user_id=event.get_user_id(), user_id=event.get_user_id(),

View File

@ -12,6 +12,7 @@ Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
from croterline.process import get_ctx from croterline.process import get_ctx
from nonebot.adapters.onebot.v11 import MessageEvent from nonebot.adapters.onebot.v11 import MessageEvent
from nonebot.plugin import PluginMetadata from nonebot.plugin import PluginMetadata
from nonebot.log import logger
from nonebot import on_message from nonebot import on_message
__plugin_meta__ = PluginMetadata( __plugin_meta__ = PluginMetadata(
@ -20,11 +21,13 @@ __plugin_meta__ = PluginMetadata(
usage="用户无需使用", usage="用户无需使用",
) )
ctx = get_ctx() ctx = get_ctx()
@on_message().handle() @on_message(block=False, priority=100).handle()
async def _(event: MessageEvent): async def _(event: MessageEvent):
print("Push message to Liteyuki") logger.debug("Pushing message to Liteyuki")
ctx.sub_chan << event.raw_message ctx.sub_chan << event.raw_message
logger.debug("Pushed message to Liteyuki")

View File

@ -1,9 +1,6 @@
import time import time
from typing import AnyStr from typing import AnyStr
import time
from typing import AnyStr
import nonebot import nonebot
import pip import pip
from nonebot import get_driver, require from nonebot import get_driver, require
@ -14,15 +11,15 @@ from nonebot.permission import SUPERUSER
# from src.liteyuki.core import Reloader # from src.liteyuki.core import Reloader
from src.utils import event as event_utils, satori_utils from src.utils import event as event_utils, satori_utils
from src.utils.base import reload # type: ignore
from src.utils.base.config import get_config from src.utils.base.config import get_config
from src.utils.base.data_manager import TempConfig, common_db from src.utils.base.data_manager import TempConfig, common_db
from src.utils.base.language import get_user_lang from src.utils.base.language import get_user_lang
from src.utils.base.ly_function import get_function # type: ignore
from src.utils.base.ly_typing import T_Bot, T_MessageEvent from src.utils.base.ly_typing import T_Bot, T_MessageEvent
from src.utils.message.html_tool import md_to_pic
from src.utils.message.message import MarkdownMessage as md, broadcast_to_superusers from src.utils.message.message import MarkdownMessage as md, broadcast_to_superusers
from .api import update_liteyuki # type: ignore from .api import update_liteyuki # type: ignore
from src.utils.base import reload # type: ignore
from src.utils.base.ly_function import get_function # type: ignore
from src.utils.message.html_tool import md_to_pic
require("nonebot_plugin_alconna") require("nonebot_plugin_alconna")
require("nonebot_plugin_apscheduler") require("nonebot_plugin_apscheduler")

View File

@ -4,14 +4,12 @@ from pathlib import Path
import nonebot.plugin import nonebot.plugin
from nonebot import get_driver from nonebot import get_driver
from src.utils import init_log
from src.utils.base.config import get_config from src.utils.base.config import get_config
from src.utils.base.data_manager import InstalledPlugin, plugin_db from src.utils.base.data_manager import InstalledPlugin, plugin_db
from src.utils.base.resource import load_resources from src.utils.base.resource import load_resources
from src.utils.message.tools import check_for_package from src.utils.message.tools import check_for_package
load_resources() load_resources()
init_log()
driver = get_driver() driver = get_driver()

View File

@ -6,7 +6,6 @@ __NAME__ = "LiteyukiBot"
__VERSION__ = "6.3.2" # 60201 __VERSION__ = "6.3.2" # 60201
from src.utils.base.config import load_from_yaml, config from src.utils.base.config import load_from_yaml, config
from src.utils.base.log import init_log
from git import Repo from git import Repo
major, minor, patch = map(int, __VERSION__.split(".")) major, minor, patch = map(int, __VERSION__.split("."))
@ -20,7 +19,6 @@ def init():
""" """
# 检测python版本是否高于3.10 # 检测python版本是否高于3.10
init_log()
if sys.version_info < (3, 10): if sys.version_info < (3, 10):
nonebot.logger.error("Requires Python3.10+ to run, please upgrade your Python Environment.") nonebot.logger.error("Requires Python3.10+ to run, please upgrade your Python Environment.")
exit(1) exit(1)

View File

@ -1,79 +1,79 @@
import sys # import sys
import loguru # import loguru
from typing import TYPE_CHECKING # from typing import TYPE_CHECKING
from .config import load_from_yaml # from .config import load_from_yaml
from .language import Language, get_default_lang_code # from .language import Language, get_default_lang_code
#
logger = loguru.logger # logger = loguru.logger
if TYPE_CHECKING: # if TYPE_CHECKING:
# avoid sphinx autodoc resolve annotation failed # # avoid sphinx autodoc resolve annotation failed
# because loguru module do not have `Logger` class actually # # because loguru module do not have `Logger` class actually
from loguru import Record # from loguru import Record
#
#
def default_filter(record: "Record"): # def default_filter(record: "Record"):
"""默认的日志过滤器,根据 `config.log_level` 配置改变日志等级。""" # """默认的日志过滤器,根据 `config.log_level` 配置改变日志等级。"""
log_level = record["extra"].get("nonebot_log_level", "INFO") # log_level = record["extra"].get("nonebot_log_level", "INFO")
levelno = logger.level(log_level).no if isinstance(log_level, str) else log_level # levelno = logger.level(log_level).no if isinstance(log_level, str) else log_level
return record["level"].no >= levelno # return record["level"].no >= levelno
#
#
# DEBUG日志格式 # # DEBUG日志格式
debug_format: str = ( # debug_format: str = (
"<c>{time:YYYY-MM-DD HH:mm:ss}</c> " # "<c>{time:YYYY-MM-DD HH:mm:ss}</c> "
"<lvl>[{level.icon}]</lvl> " # "<lvl>[{level.icon}]</lvl> "
"<c><{name}.{module}.{function}:{line}></c> " # "<c><{name}.{module}.{function}:{line}></c> "
"{message}" # "{message}"
) # )
#
# 默认日志格式 # # 默认日志格式
default_format: str = ( # default_format: str = (
"<c>{time:MM-DD HH:mm:ss}</c> " # "<c>{time:MM-DD HH:mm:ss}</c> "
"<lvl>[{level.icon}]</lvl> " # "<lvl>[{level.icon}]</lvl> "
"<c><{name}></c> " # "<c><{name}></c> "
"{message}" # "{message}"
) # )
#
#
def get_format(level: str) -> str: # def get_format(level: str) -> str:
if level == "DEBUG": # if level == "DEBUG":
return debug_format # return debug_format
else: # else:
return default_format # return default_format
#
#
logger = loguru.logger.bind() # logger = loguru.logger.bind()
#
#
def init_log(): # def init_log():
""" # """
在语言加载完成后执行 # 在语言加载完成后执行
Returns: # Returns:
#
""" # """
global logger # global logger
#
config = load_from_yaml("config.yml") # config = load_from_yaml("config.yml")
#
logger.remove() # logger.remove()
logger.add( # logger.add(
sys.stdout, # sys.stdout,
level=0, # level=0,
diagnose=False, # diagnose=False,
filter=default_filter, # filter=default_filter,
format=get_format(config.get("log_level", "INFO")), # format=get_format(config.get("log_level", "INFO")),
) # )
show_icon = config.get("log_icon", True) # show_icon = config.get("log_icon", True)
lang = Language(get_default_lang_code()) # lang = Language(get_default_lang_code())
#
debug = lang.get("log.debug", default="==DEBUG") # debug = lang.get("log.debug", default="==DEBUG")
info = lang.get("log.info", default="===INFO") # info = lang.get("log.info", default="===INFO")
success = lang.get("log.success", default="SUCCESS") # success = lang.get("log.success", default="SUCCESS")
warning = lang.get("log.warning", default="WARNING") # warning = lang.get("log.warning", default="WARNING")
error = lang.get("log.error", default="==ERROR") # error = lang.get("log.error", default="==ERROR")
#
logger.level("DEBUG", color="<blue>", icon=f"{'🐛' if show_icon else ''}{debug}") # logger.level("DEBUG", color="<blue>", icon=f"{'🐛' if show_icon else ''}{debug}")
logger.level("INFO", color="<normal>", icon=f"{'' if show_icon else ''}{info}") # logger.level("INFO", color="<normal>", icon=f"{'' if show_icon else ''}{info}")
logger.level("SUCCESS", color="<green>", icon=f"{'' if show_icon else ''}{success}") # logger.level("SUCCESS", color="<green>", icon=f"{'✅' if show_icon else ''}{success}")
logger.level("WARNING", color="<yellow>", icon=f"{'⚠️' if show_icon else ''}{warning}") # logger.level("WARNING", color="<yellow>", icon=f"{'⚠️' if show_icon else ''}{warning}")
logger.level("ERROR", color="<red>", icon=f"{'' if show_icon else ''}{error}") # logger.level("ERROR", color="<red>", icon=f"{'⭕' if show_icon else ''}{error}")

9
tests/test_logger.py Normal file
View File

@ -0,0 +1,9 @@
from liteyuki import logger
def test_logger():
logger.info('Hello, World!')
logger.debug('Hello, World!')
logger.warning('Hello, World!')
logger.error('Hello, World!')
logger.critical('Hello, World!')
logger.success("Hello, World!")