Skip to content

Commit

Permalink
🍻 use FormatFunction in log
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Jan 23, 2025
1 parent 7c372b8 commit e8c8943
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 31 deletions.
42 changes: 22 additions & 20 deletions arclet/entari/builtins/auto_reload.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,26 +73,28 @@ async def watch(self):
for change in event:
if plugin := find_plugin_by_file(change[1]):
if plugin.is_static:
logger("INFO", f"Plugin <y>{plugin.id!r}</y> is static, ignored.")
logger.opt(colors=True).info(f"Plugin <y>{plugin.id!r}</y> is static, ignored.")
continue
logger("INFO", f"Detected change in <blue>{plugin.id!r}</blue>, reloading...")
logger.opt(colors=True).info(f"Detected change in <blue>{plugin.id!r}</blue>, reloading...")
pid = plugin.id
del plugin
unload_plugin(pid)
if plugin := load_plugin(pid):
logger("INFO", f"Reloaded <blue>{plugin.id!r}</blue>")
logger.opt(colors=True).info(f"Reloaded <blue>{plugin.id!r}</blue>")
del plugin
else:
logger("ERROR", f"Failed to reload <blue>{pid!r}</blue>")
logger.opt(colors=True).error(f"Failed to reload <blue>{pid!r}</blue>")
self.fail[change[1]] = pid
elif change[1] in self.fail:
logger("INFO", f"Detected change in {change[1]!r} which failed to reload, retrying...")
logger.opt(colors=True).info(
f"Detected change in {change[1]!r} which failed to reload, retrying..."
)
if plugin := load_plugin(self.fail[change[1]]):
logger("INFO", f"Reloaded <blue>{plugin.id!r}</blue>")
logger.opt(colors=True).info(f"Reloaded <blue>{plugin.id!r}</blue>")
del plugin
del self.fail[change[1]]
else:
logger("ERROR", f"Failed to reload <blue>{self.fail[change[1]]!r}</blue>")
logger.opt(colors=True).error(f"Failed to reload <blue>{self.fail[change[1]]!r}</blue>")

async def watch_config(self):
file = EntariConfig.instance.path.resolve()
Expand All @@ -108,21 +110,20 @@ async def watch_config(self):
):
print(change)
continue
logger("INFO", f"Detected change in {change[1]!r}, reloading config...")
logger.opt(colors=True).info(f"Detected change in {change[1]!r}, reloading config...")

old_basic = EntariConfig.instance.basic.copy()
old_plugin = EntariConfig.instance.plugin.copy()
EntariConfig.instance.reload()
for key in old_basic:
if key in EntariConfig.instance.basic and old_basic[key] != EntariConfig.instance.basic[key]:
logger(
"DEBUG",
logger.opt(colors=True).debug(
f"Basic config <y>{key!r}</y> changed from <r>{old_basic[key]!r}</r> "
f"to <g>{EntariConfig.instance.basic[key]!r}</g>",
)
await es.publish(ConfigReload("basic", key, EntariConfig.instance.basic[key], old_basic[key]))
for key in set(EntariConfig.instance.basic) - set(old_basic):
logger("DEBUG", f"Basic config <y>{key!r}</y> appended")
logger.opt(colors=True).debug(f"Basic config <y>{key!r}</y> appended")
await es.publish(ConfigReload("basic", key, EntariConfig.instance.basic[key]))
for plugin_name in old_plugin:
if plugin_name.startswith("$") or plugin_name.startswith("~"):
Expand All @@ -132,11 +133,10 @@ async def watch_config(self):
if plugin := find_plugin(pid):
del plugin
unload_plugin(pid)
logger("INFO", f"Disposed plugin <blue>{pid!r}</blue>")
logger.opt(colors=True).info(f"Disposed plugin <blue>{pid!r}</blue>")
continue
if old_plugin[plugin_name] != EntariConfig.instance.plugin[plugin_name]:
logger(
"DEBUG",
logger.opt(colors=True).debug(
f"Plugin <y>{plugin_name!r}</y> config changed from <r>{old_plugin[plugin_name]!r}</r> "
f"to <g>{EntariConfig.instance.plugin[plugin_name]!r}</g>",
)
Expand All @@ -146,25 +146,27 @@ async def watch_config(self):
allow, deny, only_filter = detect_filter_change(old_conf, new_conf)
plugin.update_filter(allow, deny)
if only_filter:
logger("DEBUG", f"Plugin <y>{pid!r}</y> config only changed filter.")
logger.opt(colors=True).debug(f"Plugin <y>{pid!r}</y> config only changed filter.")
continue
res = await es.post(
ConfigReload("plugin", plugin_name, new_conf, old_conf),
)
if res and res.value:
logger("DEBUG", f"Plugin <y>{pid!r}</y> config change handled by itself.")
logger.opt(colors=True).debug(f"Plugin <y>{pid!r}</y> config change handled by itself.")
continue
logger("INFO", f"Detected config of <blue>{pid!r}</blue> changed, reloading...")
logger.opt(colors=True).info(
f"Detected config of <blue>{pid!r}</blue> changed, reloading..."
)
plugin_file = str(plugin.module.__file__)
unload_plugin(plugin_name)
if plugin := load_plugin(plugin_name, new_conf):
logger("INFO", f"Reloaded <blue>{plugin.id!r}</blue>")
logger.opt(colors=True).info(f"Reloaded <blue>{plugin.id!r}</blue>")
del plugin
else:
logger("ERROR", f"Failed to reload <blue>{plugin_name!r}</blue>")
logger.opt(colors=True).error(f"Failed to reload <blue>{plugin_name!r}</blue>")
self.fail[plugin_file] = pid
else:
logger("INFO", f"Detected <blue>{pid!r}</blue> appended, loading...")
logger.opt(colors=True).info(f"Detected <blue>{pid!r}</blue> appended, loading...")
load_plugin(plugin_name, new_conf)
if new := (set(EntariConfig.instance.plugin) - set(old_plugin)):
for plugin_name in new:
Expand Down
6 changes: 3 additions & 3 deletions arclet/entari/event/send.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
from ..message import MessageChain

if TYPE_CHECKING:
from ..session import SatoriEvent, Session
from ..session import Session


@dataclass
class SendRequest:
account: Account
channel: str
message: MessageChain
session: Union["Session[SatoriEvent]", None] = None
session: Union["Session", None] = None

async def gather(self, context: Contexts):
context["account"] = self.account
Expand All @@ -39,7 +39,7 @@ class SendResponse:
channel: str
message: MessageChain
result: list[MessageReceipt]
session: Union["Session[SatoriEvent]", None] = None
session: Union["Session", None] = None

async def gather(self, context: Contexts):
context["account"] = self.account
Expand Down
27 changes: 20 additions & 7 deletions arclet/entari/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,12 @@ def message(self):
return self.loggers["[message]"]

def wrapper(self, name: str, color: str = "blue"):
patched = logger.patch(lambda r: r.update(name="entari"))
patched = logger.patch(
lambda r: r.update(name="entari", extra={"entari_plugin_name": name, "entari_plugin_color": color})
)
patched = patched.bind(name=f"plugins.{name}")
self.loggers[f"plugin.{name}"] = patched

def _log(level: str, message: str, exception: Exception | None = None):
patched.opt(colors=True, exception=exception).log(level, f"| <{color}>{name}</{color}> {message}")

return _log
return patched

@staticmethod
def set_level(level: str | int):
Expand Down Expand Up @@ -90,6 +88,21 @@ def default_filter(record):
return record["level"].no >= levelno


def _custom_format(record: Record):
if "entari_plugin_name" in record["extra"]:
plugin = (
f" <{record['extra']['entari_plugin_color']}>"
f"{record['extra']['entari_plugin_name']}"
f"</{record['extra']['entari_plugin_color']}>"
)
else:
plugin = ""
return (
f"<lk>{{time:YYYY-MM-DD HH:mm:ss}}</lk> <lvl>{{level}}</lvl> | <m><u>{{name}}</u></m>"
f"{plugin} <lvl>{{message}}</lvl>\n"
)


logger.remove()
logger_id = logger.add(
sys.stdout,
Expand All @@ -98,7 +111,7 @@ def default_filter(record):
backtrace=True,
colorize=True,
filter=default_filter,
format="<lk>{time:YYYY-MM-DD HH:mm:ss}</lk> <lvl>{level:8}</lvl> | <m><u>{name}</u></m> <lvl>{message}</lvl>",
format=_custom_format,
)
"""默认日志处理器 id"""

Expand Down
2 changes: 1 addition & 1 deletion example_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ async def show(session: Session):
await session.send_message(f"Execute `echo 123` Result: {res}")
return f"Data: {kept_data}"

TEST = 5
TEST = 6

print([*Plugin.current()._scope.subscribers])
print(Plugin.current().subplugins)
Expand Down

0 comments on commit e8c8943

Please sign in to comment.