mirror of
				https://github.com/nonebot/nonebot2.git
				synced 2025-10-31 15:06:42 +00:00 
			
		
		
		
	🔇 Feature: 调整日志输出格式与等级 (#1233)
This commit is contained in:
		| @@ -33,6 +33,9 @@ class Adapter(abc.ABC): | ||||
|         self.bots: Dict[str, Bot] = {} | ||||
|         """本协议适配器已建立连接的 {ref}`nonebot.adapters.Bot` 实例""" | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return f"Adapter(name={self.get_name()!r})" | ||||
|  | ||||
|     @classmethod | ||||
|     @abc.abstractmethod | ||||
|     def get_name(cls) -> str: | ||||
|   | ||||
| @@ -13,10 +13,9 @@ if TYPE_CHECKING: | ||||
|     from .adapter import Adapter | ||||
|     from .message import Message, MessageSegment | ||||
|  | ||||
|  | ||||
| class _ApiCall(Protocol): | ||||
|     async def __call__(self, **kwargs: Any) -> Any: | ||||
|         ... | ||||
|     class _ApiCall(Protocol): | ||||
|         async def __call__(self, **kwargs: Any) -> Any: | ||||
|             ... | ||||
|  | ||||
|  | ||||
| class Bot(abc.ABC): | ||||
| @@ -40,7 +39,10 @@ class Bot(abc.ABC): | ||||
|         self.self_id: str = self_id | ||||
|         """机器人 ID""" | ||||
|  | ||||
|     def __getattr__(self, name: str) -> _ApiCall: | ||||
|     def __repr__(self) -> str: | ||||
|         return f"Bot(type={self.type!r}, self_id={self.self_id!r})" | ||||
|  | ||||
|     def __getattr__(self, name: str) -> "_ApiCall": | ||||
|         return partial(self.call_api, name) | ||||
|  | ||||
|     @property | ||||
|   | ||||
| @@ -56,6 +56,9 @@ class MessageTemplate(Formatter, Generic[TF]): | ||||
|         self.factory: Type[TF] = factory | ||||
|         self.format_specs: Dict[str, FormatSpecFunc] = {} | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return f"MessageTemplate({self.template!r}, factory={self.factory!r})" | ||||
|  | ||||
|     def add_format_spec( | ||||
|         self, spec: FormatSpecFunc_T, name: Optional[str] = None | ||||
|     ) -> FormatSpecFunc_T: | ||||
|   | ||||
| @@ -40,12 +40,18 @@ class Driver(abc.ABC): | ||||
|         """环境名称""" | ||||
|         self.config: Config = config | ||||
|         """全局配置对象""" | ||||
|         self._clients: Dict[str, "Bot"] = {} | ||||
|         self._bots: Dict[str, "Bot"] = {} | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return ( | ||||
|             f"Driver(type={self.type!r}, " | ||||
|             f"adapters={len(self._adapters)}, bots={len(self._bots)})" | ||||
|         ) | ||||
|  | ||||
|     @property | ||||
|     def bots(self) -> Dict[str, "Bot"]: | ||||
|         """获取当前所有已连接的 Bot""" | ||||
|         return self._clients | ||||
|         return self._bots | ||||
|  | ||||
|     def register_adapter(self, adapter: Type["Adapter"], **kwargs) -> None: | ||||
|         """注册一个协议适配器 | ||||
| @@ -124,9 +130,9 @@ class Driver(abc.ABC): | ||||
|  | ||||
|     def _bot_connect(self, bot: "Bot") -> None: | ||||
|         """在连接成功后,调用该函数来注册 bot 对象""" | ||||
|         if bot.self_id in self._clients: | ||||
|         if bot.self_id in self._bots: | ||||
|             raise RuntimeError(f"Duplicate bot connection with id {bot.self_id}") | ||||
|         self._clients[bot.self_id] = bot | ||||
|         self._bots[bot.self_id] = bot | ||||
|  | ||||
|         async def _run_hook(bot: "Bot") -> None: | ||||
|             coros = list( | ||||
| @@ -148,8 +154,8 @@ class Driver(abc.ABC): | ||||
|  | ||||
|     def _bot_disconnect(self, bot: "Bot") -> None: | ||||
|         """在连接断开后,调用该函数来注销 bot 对象""" | ||||
|         if bot.self_id in self._clients: | ||||
|             del self._clients[bot.self_id] | ||||
|         if bot.self_id in self._bots: | ||||
|             del self._bots[bot.self_id] | ||||
|  | ||||
|         async def _run_hook(bot: "Bot") -> None: | ||||
|             coros = list( | ||||
|   | ||||
| @@ -131,9 +131,7 @@ class Request: | ||||
|                     self.files.append((name, file_info))  # type: ignore | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         class_name = self.__class__.__name__ | ||||
|         url = str(self.url) | ||||
|         return f"<{class_name}({self.method!r}, {url!r})>" | ||||
|         return f"{self.__class__.__name__}(method={self.method!r}, url='{self.url!s}')" | ||||
|  | ||||
|  | ||||
| class Response: | ||||
| @@ -161,12 +159,18 @@ class Response: | ||||
|         # request | ||||
|         self.request: Optional[Request] = request | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return f"{self.__class__.__name__}(status_code={self.status_code!r})" | ||||
|  | ||||
|  | ||||
| class WebSocket(abc.ABC): | ||||
|     def __init__(self, *, request: Request): | ||||
|         # request | ||||
|         self.request: Request = request | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return f"{self.__class__.__name__}('{self.request.url!s}')" | ||||
|  | ||||
|     @property | ||||
|     @abc.abstractmethod | ||||
|     def closed(self) -> bool: | ||||
| @@ -320,17 +324,14 @@ class Cookies(MutableMapping): | ||||
|         return len(self.jar) | ||||
|  | ||||
|     def __iter__(self) -> Iterator[Cookie]: | ||||
|         return (cookie for cookie in self.jar) | ||||
|         return iter(self.jar) | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         cookies_repr = ", ".join( | ||||
|             [ | ||||
|                 f"<Cookie {cookie.name}={cookie.value} for {cookie.domain} />" | ||||
|                 for cookie in self.jar | ||||
|             ] | ||||
|             f"Cookie({cookie.name}={cookie.value} for {cookie.domain})" | ||||
|             for cookie in self.jar | ||||
|         ) | ||||
|  | ||||
|         return f"<Cookies [{cookies_repr}]>" | ||||
|         return f"{self.__class__.__name__}({cookies_repr})" | ||||
|  | ||||
|  | ||||
| @dataclass | ||||
|   | ||||
| @@ -36,7 +36,6 @@ from nonebot.typing import ( | ||||
|     T_PermissionUpdater, | ||||
| ) | ||||
| from nonebot.exception import ( | ||||
|     TypeMisMatch, | ||||
|     PausedException, | ||||
|     StopPropagation, | ||||
|     SkippedException, | ||||
| @@ -73,29 +72,16 @@ current_handler: ContextVar[Dependent] = ContextVar("current_handler") | ||||
|  | ||||
| class MatcherMeta(type): | ||||
|     if TYPE_CHECKING: | ||||
|         module: Optional[str] | ||||
|         plugin_name: Optional[str] | ||||
|         module_name: Optional[str] | ||||
|         module_prefix: Optional[str] | ||||
|         type: str | ||||
|         rule: Rule | ||||
|         permission: Permission | ||||
|         handlers: List[T_Handler] | ||||
|         priority: int | ||||
|         block: bool | ||||
|         temp: bool | ||||
|         expire_time: Optional[datetime] | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return ( | ||||
|             f"<Matcher from {self.module_name or 'unknown'}, " | ||||
|             f"type={self.type}, priority={self.priority}, " | ||||
|             f"temp={self.temp}>" | ||||
|             f"Matcher(type={self.type!r}" | ||||
|             + (f", module={self.module_name}" if self.module_name else "") | ||||
|             + ")" | ||||
|         ) | ||||
|  | ||||
|     def __str__(self) -> str: | ||||
|         return repr(self) | ||||
|  | ||||
|  | ||||
| class Matcher(metaclass=MatcherMeta): | ||||
|     """事件响应器类""" | ||||
| @@ -150,8 +136,9 @@ class Matcher(metaclass=MatcherMeta): | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return ( | ||||
|             f"<Matcher from {self.module_name or 'unknown'}, type={self.type}, " | ||||
|             f"priority={self.priority}, temp={self.temp}>" | ||||
|             f"Matcher(type={self.type!r}" | ||||
|             + (f", module={self.module_name}" if self.module_name else "") | ||||
|             + ")" | ||||
|         ) | ||||
|  | ||||
|     @classmethod | ||||
| @@ -683,8 +670,8 @@ class Matcher(metaclass=MatcherMeta): | ||||
|         dependency_cache: Optional[T_DependencyCache] = None, | ||||
|     ): | ||||
|         logger.trace( | ||||
|             f"Matcher {self} run with incoming args: " | ||||
|             f"bot={bot}, event={event}, state={state}" | ||||
|             f"{self} run with incoming args: " | ||||
|             f"bot={bot}, event={event!r}, state={state!r}" | ||||
|         ) | ||||
|         b_t = current_bot.set(bot) | ||||
|         e_t = current_event.set(event) | ||||
| @@ -706,17 +693,12 @@ class Matcher(metaclass=MatcherMeta): | ||||
|                         stack=stack, | ||||
|                         dependency_cache=dependency_cache, | ||||
|                     ) | ||||
|                 except TypeMisMatch as e: | ||||
|                     logger.debug( | ||||
|                         f"Handler {handler} param {e.param.name} value {e.value} " | ||||
|                         f"mismatch type {e.param._type_display()}, skipped" | ||||
|                     ) | ||||
|                 except SkippedException as e: | ||||
|                 except SkippedException: | ||||
|                     logger.debug(f"Handler {handler} skipped") | ||||
|         except StopPropagation: | ||||
|             self.block = True | ||||
|         finally: | ||||
|             logger.info(f"Matcher {self} running complete") | ||||
|             logger.info(f"{self} running complete") | ||||
|             current_bot.reset(b_t) | ||||
|             current_event.reset(e_t) | ||||
|             current_matcher.reset(m_t) | ||||
|   | ||||
| @@ -36,7 +36,7 @@ class DependsInner: | ||||
|     def __repr__(self) -> str: | ||||
|         dep = get_name(self.dependency) | ||||
|         cache = "" if self.use_cache else ", use_cache=False" | ||||
|         return f"{self.__class__.__name__}({dep}{cache})" | ||||
|         return f"DependsInner({dep}{cache})" | ||||
|  | ||||
|  | ||||
| def Depends( | ||||
| @@ -71,6 +71,9 @@ def Depends( | ||||
| class DependParam(Param): | ||||
|     """子依赖参数""" | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return f"Depends({self.extra['dependent']})" | ||||
|  | ||||
|     @classmethod | ||||
|     def _check_param( | ||||
|         cls, param: inspect.Parameter, allow_types: Tuple[Type[Param], ...] | ||||
| @@ -153,6 +156,17 @@ class DependParam(Param): | ||||
| class BotParam(Param): | ||||
|     """{ref}`nonebot.adapters.Bot` 参数""" | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return ( | ||||
|             "BotParam(" | ||||
|             + ( | ||||
|                 repr(cast(ModelField, checker).type_) | ||||
|                 if (checker := self.extra.get("checker")) | ||||
|                 else "" | ||||
|             ) | ||||
|             + ")" | ||||
|         ) | ||||
|  | ||||
|     @classmethod | ||||
|     def _check_param( | ||||
|         cls, param: inspect.Parameter, allow_types: Tuple[Type[Param], ...] | ||||
| @@ -179,13 +193,24 @@ class BotParam(Param): | ||||
|         return bot | ||||
|  | ||||
|     async def _check(self, bot: "Bot", **kwargs: Any) -> None: | ||||
|         if checker := self.extra.get("checker", None): | ||||
|         if checker := self.extra.get("checker"): | ||||
|             check_field_type(checker, bot) | ||||
|  | ||||
|  | ||||
| class EventParam(Param): | ||||
|     """{ref}`nonebot.adapters.Event` 参数""" | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return ( | ||||
|             "EventParam(" | ||||
|             + ( | ||||
|                 repr(cast(ModelField, checker).type_) | ||||
|                 if (checker := self.extra.get("checker")) | ||||
|                 else "" | ||||
|             ) | ||||
|             + ")" | ||||
|         ) | ||||
|  | ||||
|     @classmethod | ||||
|     def _check_param( | ||||
|         cls, param: inspect.Parameter, allow_types: Tuple[Type[Param], ...] | ||||
| @@ -216,20 +241,17 @@ class EventParam(Param): | ||||
|             check_field_type(checker, event) | ||||
|  | ||||
|  | ||||
| class StateInner(T_State): | ||||
|     ... | ||||
|  | ||||
|  | ||||
| class StateParam(Param): | ||||
|     """事件处理状态参数""" | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return "StateParam()" | ||||
|  | ||||
|     @classmethod | ||||
|     def _check_param( | ||||
|         cls, param: inspect.Parameter, allow_types: Tuple[Type[Param], ...] | ||||
|     ) -> Optional["StateParam"]: | ||||
|         if isinstance(param.default, StateInner): | ||||
|             return cls(Required) | ||||
|         elif param.default == param.empty: | ||||
|         if param.default == param.empty: | ||||
|             if param.annotation is T_State: | ||||
|                 return cls(Required) | ||||
|             elif param.annotation == param.empty and param.name == "state": | ||||
| @@ -242,6 +264,9 @@ class StateParam(Param): | ||||
| class MatcherParam(Param): | ||||
|     """事件响应器实例参数""" | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return "MatcherParam()" | ||||
|  | ||||
|     @classmethod | ||||
|     def _check_param( | ||||
|         cls, param: inspect.Parameter, allow_types: Tuple[Type[Param], ...] | ||||
| @@ -264,6 +289,9 @@ class ArgInner: | ||||
|         self.key = key | ||||
|         self.type = type | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return f"ArgInner(key={self.key!r}, type={self.type!r})" | ||||
|  | ||||
|  | ||||
| def Arg(key: Optional[str] = None) -> Any: | ||||
|     """`got` 的 Arg 参数消息""" | ||||
| @@ -283,6 +311,9 @@ def ArgPlainText(key: Optional[str] = None) -> str: | ||||
| class ArgParam(Param): | ||||
|     """`got` 的 Arg 参数""" | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return f"ArgParam(key={self.extra['key']!r}, type={self.extra['type']!r})" | ||||
|  | ||||
|     @classmethod | ||||
|     def _check_param( | ||||
|         cls, param: inspect.Parameter, allow_types: Tuple[Type[Param], ...] | ||||
| @@ -307,6 +338,9 @@ class ArgParam(Param): | ||||
| class ExceptionParam(Param): | ||||
|     """`run_postprocessor` 的异常参数""" | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return "ExceptionParam()" | ||||
|  | ||||
|     @classmethod | ||||
|     def _check_param( | ||||
|         cls, param: inspect.Parameter, allow_types: Tuple[Type[Param], ...] | ||||
| @@ -323,6 +357,9 @@ class ExceptionParam(Param): | ||||
| class DefaultParam(Param): | ||||
|     """默认值参数""" | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return f"DefaultParam(default={self.default!r})" | ||||
|  | ||||
|     @classmethod | ||||
|     def _check_param( | ||||
|         cls, param: inspect.Parameter, allow_types: Tuple[Type[Param], ...] | ||||
|   | ||||
| @@ -47,6 +47,9 @@ class Permission: | ||||
|         } | ||||
|         """存储 `PermissionChecker`""" | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return f"Permission({', '.join(repr(checker) for checker in self.checkers)})" | ||||
|  | ||||
|     async def __call__( | ||||
|         self, | ||||
|         bot: Bot, | ||||
| @@ -121,6 +124,13 @@ class User: | ||||
|         self.users = users | ||||
|         self.perm = perm | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return ( | ||||
|             f"User(users={self.users}" | ||||
|             + (f", permission={self.perm})" if self.perm else "") | ||||
|             + ")" | ||||
|         ) | ||||
|  | ||||
|     async def __call__(self, bot: Bot, event: Event) -> bool: | ||||
|         return bool( | ||||
|             event.get_session_id() in self.users | ||||
|   | ||||
| @@ -47,6 +47,9 @@ class Rule: | ||||
|         } | ||||
|         """存储 `RuleChecker`""" | ||||
|  | ||||
|     def __repr__(self) -> str: | ||||
|         return f"Rule({', '.join(repr(checker) for checker in self.checkers)})" | ||||
|  | ||||
|     async def __call__( | ||||
|         self, | ||||
|         bot: Bot, | ||||
|   | ||||
		Reference in New Issue
	
	Block a user