Skip to content

Commit

Permalink
feat(log): 将 error_or_exception() 函数更改为 Bot 类的一个方法 (#72)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: 删除了 log 模块的 error_or_exception() 函数,请使用 Bot 类的同名函数替代
  • Loading branch information
st1020 committed Aug 15, 2023
1 parent e22bea5 commit c1addba
Show file tree
Hide file tree
Showing 9 changed files with 39 additions and 84 deletions.
7 changes: 2 additions & 5 deletions alicebot/adapter/__init__.py
Expand Up @@ -19,7 +19,6 @@
)

from alicebot.event import Event
from alicebot.log import error_or_exception
from alicebot.typing import ConfigT, EventT
from alicebot.utils import is_config_class

Expand Down Expand Up @@ -78,10 +77,8 @@ async def safe_run(self) -> None:
try:
await self.run()
except Exception as e:
error_or_exception(
f"Run adapter {self.__class__.__name__} failed:",
e,
self.bot.config.bot.log.verbose_exception,
self.bot.error_or_exception(
f"Run adapter {self.__class__.__name__} failed:", e
)

@abstractmethod
Expand Down
8 changes: 2 additions & 6 deletions alicebot/adapter/utils.py
Expand Up @@ -10,7 +10,7 @@
from aiohttp import web

from alicebot.adapter import Adapter
from alicebot.log import error_or_exception, logger
from alicebot.log import logger
from alicebot.typing import ConfigT, EventT

__all__ = [
Expand Down Expand Up @@ -216,11 +216,7 @@ async def run(self) -> None:
try:
await self.websocket_connect()
except aiohttp.ClientError as e:
error_or_exception(
"WebSocket connection error:",
e,
self.bot.config.bot.log.verbose_exception,
)
self.bot.error_or_exception("WebSocket connection error:", e)
if self.bot.should_exit.is_set():
break
await asyncio.sleep(self.reconnect_interval)
Expand Down
55 changes: 21 additions & 34 deletions alicebot/bot.py
Expand Up @@ -39,7 +39,7 @@
SkipException,
StopException,
)
from alicebot.log import error_or_exception, logger
from alicebot.log import logger
from alicebot.plugin import Plugin, PluginLoadType
from alicebot.typing import AdapterHook, AdapterT, BotHook, EventHook, EventT
from alicebot.utils import (
Expand Down Expand Up @@ -225,11 +225,7 @@ async def _run(self) -> None:
try:
await _adapter.startup()
except Exception as e:
error_or_exception(
f"Startup adapter {_adapter!r} failed:",
e,
self.config.bot.log.verbose_exception,
)
self.error_or_exception(f"Startup adapter {_adapter!r} failed:", e)

for _adapter in self.adapters:
for adapter_run_hook_func in self._adapter_run_hooks:
Expand Down Expand Up @@ -403,23 +399,15 @@ def _reload_config_dict(self) -> None:
else:
logger.error("Unable to determine config file type")
except OSError as e:
error_or_exception(
"Can not open config file:",
e,
self.config.bot.log.verbose_exception,
)
self.error_or_exception("Can not open config file:", e)
except (ValueError, json.JSONDecodeError, tomllib.TOMLDecodeError) as e:
error_or_exception(
"Read config file failed:", e, self.config.bot.log.verbose_exception
)
self.error_or_exception("Read config file failed:", e)

try:
self.config = MainConfig(**self._raw_config_dict)
except ValidationError as e:
self.config = MainConfig()
error_or_exception(
"Config dict parse error:", e, self.config.bot.log.verbose_exception
)
self.error_or_exception("Config dict parse error:", e)
self._update_config()

def reload_plugins(self) -> None:
Expand Down Expand Up @@ -523,11 +511,7 @@ async def _handle_event(self, current_event: Optional[Event[Any]] = None) -> Non
# 插件要求停止当前事件传播
stop = True
except Exception as e:
error_or_exception(
f'Exception in plugin "{plugin}":',
e,
self.config.bot.log.verbose_exception,
)
self.error_or_exception(f'Exception in plugin "{plugin}":', e)
if stop:
break

Expand Down Expand Up @@ -662,12 +646,11 @@ def _load_plugin_class(
f'from class "{plugin_class!r}"'
)
else:
error_or_exception(
self.error_or_exception(
f'Load plugin from class "{plugin_class!r}" failed:',
LoadModuleError(
f'Plugin priority incorrect in the class "{plugin_class!r}"'
),
self.config.bot.log.verbose_exception,
)

def _load_plugins_from_module_name(
Expand All @@ -683,11 +666,7 @@ def _load_plugins_from_module_name(
module_name, Plugin, reload=reload
)
except ImportError as e:
error_or_exception(
f'Import module "{module_name}" failed:',
e,
self.config.bot.log.verbose_exception,
)
self.error_or_exception(f'Import module "{module_name}" failed:', e)
else:
for plugin_class, module in plugin_classes:
self._load_plugin_class(
Expand Down Expand Up @@ -848,11 +827,7 @@ def _load_adapters(self, *adapters: Union[Type[Adapter[Any, Any]], str]) -> None
f"Type error: {adapter_} can not be loaded as adapter"
)
except Exception as e:
error_or_exception(
f'Load adapter "{adapter_}" failed:',
e,
self.config.bot.log.verbose_exception,
)
self.error_or_exception(f'Load adapter "{adapter_}" failed:', e)
else:
self.adapters.append(adapter_object)
logger.info(
Expand Down Expand Up @@ -919,6 +894,18 @@ def get_plugin(self, name: str) -> Type[Plugin[Any, Any, Any]]:
return _plugin
raise LookupError(f'Can not find plugin named "{name}"')

def error_or_exception(self, message: str, exception: Exception) -> None:
"""根据当前 Bot 的配置输出 error 或者 exception 日志。
Args:
message: 消息。
exception: 异常。
"""
if self.config.bot.log.verbose_exception:
logger.exception(message)
else:
logger.error(f"{message} {exception!r}")

def bot_run_hook(self, func: BotHook) -> BotHook:
"""注册一个 Bot 启动时的函数。
Expand Down
16 changes: 1 addition & 15 deletions alicebot/log.py
Expand Up @@ -5,20 +5,6 @@
"""
from loguru import logger as _logger

__all__ = ["logger", "error_or_exception"]
__all__ = ["logger"]

logger = _logger


def error_or_exception(message: str, exception: Exception, verbose: bool) -> None:
"""输出 error 或者 exception 日志。
Args:
message: 消息。
exception: 异常。
verbose: 是否使用 exception。
"""
if verbose:
logger.exception(message)
else:
logger.error(f"{message} {exception!r}") # noqa: G004
Expand Up @@ -11,7 +11,7 @@
from apscheduler.schedulers.asyncio import AsyncIOScheduler

from alicebot.adapter import Adapter
from alicebot.log import error_or_exception, logger
from alicebot.log import logger
from alicebot.plugin import Plugin
from alicebot.typing import PluginT

Expand Down Expand Up @@ -65,11 +65,10 @@ async def run(self) -> None:
self.create_event, args=(plugin,), trigger=trigger, **trigger_args
)
except Exception as e:
error_or_exception(
self.bot.error_or_exception(
f"Plugin {plugin.__name__} add_job filed, "
"please check trigger and trigger_args:",
e,
self.bot.config.bot.log.verbose_exception,
)
else:
logger.info(f"Plugin {plugin.__name__} has been scheduled to run")
Expand Down
Expand Up @@ -26,7 +26,7 @@
from aiohttp import web

from alicebot.adapter.utils import WebSocketAdapter
from alicebot.log import error_or_exception, logger
from alicebot.log import logger
from alicebot.message import BuildMessageType
from alicebot.utils import PydanticEncoder

Expand Down Expand Up @@ -114,10 +114,8 @@ async def handle_websocket_msg(self, msg: aiohttp.WSMessage) -> None:
try:
msg_dict = msg.json()
except json.JSONDecodeError as e:
error_or_exception(
"WebSocket message parsing error, not json:",
e,
self.bot.config.bot.log.verbose_exception,
self.bot.error_or_exception(
"WebSocket message parsing error, not json:", e
)
return

Expand Down
Expand Up @@ -13,7 +13,7 @@
from aiohttp import web

from alicebot.adapter import Adapter
from alicebot.log import error_or_exception, logger
from alicebot.log import logger

from .config import Config
from .event import DingTalkEvent
Expand Down Expand Up @@ -75,11 +75,7 @@ async def handler(self, request: web.Request) -> web.Response:
try:
dingtalk_event = DingTalkEvent(adapter=self, **(await request.json()))
except Exception as e:
error_or_exception(
"Request parsing error:",
e,
self.bot.config.bot.log.verbose_exception,
)
self.bot.error_or_exception("Request parsing error:", e)
return web.Response()
await self.handle_event(dingtalk_event)
return web.Response()
Expand Down
Expand Up @@ -25,7 +25,7 @@
import aiohttp

from alicebot.adapter.utils import WebSocketAdapter
from alicebot.log import error_or_exception, logger
from alicebot.log import logger
from alicebot.message import BuildMessageType
from alicebot.utils import PydanticEncoder

Expand Down Expand Up @@ -102,10 +102,8 @@ async def handle_websocket_msg(self, msg: aiohttp.WSMessage) -> None:
try:
msg_dict = msg.json()
except json.JSONDecodeError as e:
error_or_exception(
"WebSocket message parsing error, not json:",
e,
self.bot.config.bot.log.verbose_exception,
self.bot.error_or_exception(
"WebSocket message parsing error, not json:", e
)
return

Expand Down
Expand Up @@ -26,7 +26,7 @@
from aiohttp import web

from alicebot.adapter.utils import WebSocketAdapter
from alicebot.log import error_or_exception, logger
from alicebot.log import logger
from alicebot.message import BuildMessageType
from alicebot.utils import PydanticEncoder

Expand Down Expand Up @@ -122,10 +122,8 @@ async def handle_websocket_msg(self, msg: aiohttp.WSMessage) -> None:
try:
msg_dict = msg.json()
except json.JSONDecodeError as e:
error_or_exception(
"WebSocket message parsing error, not json:",
e,
self.bot.config.bot.log.verbose_exception,
self.bot.error_or_exception(
"WebSocket message parsing error, not json:", e
)
return

Expand Down

0 comments on commit c1addba

Please sign in to comment.