Skip to content

Commit e8c8943

Browse files
committed
🍻 use FormatFunction in log
1 parent 7c372b8 commit e8c8943

File tree

4 files changed

+46
-31
lines changed

4 files changed

+46
-31
lines changed

arclet/entari/builtins/auto_reload.py

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -73,26 +73,28 @@ async def watch(self):
7373
for change in event:
7474
if plugin := find_plugin_by_file(change[1]):
7575
if plugin.is_static:
76-
logger("INFO", f"Plugin <y>{plugin.id!r}</y> is static, ignored.")
76+
logger.opt(colors=True).info(f"Plugin <y>{plugin.id!r}</y> is static, ignored.")
7777
continue
78-
logger("INFO", f"Detected change in <blue>{plugin.id!r}</blue>, reloading...")
78+
logger.opt(colors=True).info(f"Detected change in <blue>{plugin.id!r}</blue>, reloading...")
7979
pid = plugin.id
8080
del plugin
8181
unload_plugin(pid)
8282
if plugin := load_plugin(pid):
83-
logger("INFO", f"Reloaded <blue>{plugin.id!r}</blue>")
83+
logger.opt(colors=True).info(f"Reloaded <blue>{plugin.id!r}</blue>")
8484
del plugin
8585
else:
86-
logger("ERROR", f"Failed to reload <blue>{pid!r}</blue>")
86+
logger.opt(colors=True).error(f"Failed to reload <blue>{pid!r}</blue>")
8787
self.fail[change[1]] = pid
8888
elif change[1] in self.fail:
89-
logger("INFO", f"Detected change in {change[1]!r} which failed to reload, retrying...")
89+
logger.opt(colors=True).info(
90+
f"Detected change in {change[1]!r} which failed to reload, retrying..."
91+
)
9092
if plugin := load_plugin(self.fail[change[1]]):
91-
logger("INFO", f"Reloaded <blue>{plugin.id!r}</blue>")
93+
logger.opt(colors=True).info(f"Reloaded <blue>{plugin.id!r}</blue>")
9294
del plugin
9395
del self.fail[change[1]]
9496
else:
95-
logger("ERROR", f"Failed to reload <blue>{self.fail[change[1]]!r}</blue>")
97+
logger.opt(colors=True).error(f"Failed to reload <blue>{self.fail[change[1]]!r}</blue>")
9698

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

113115
old_basic = EntariConfig.instance.basic.copy()
114116
old_plugin = EntariConfig.instance.plugin.copy()
115117
EntariConfig.instance.reload()
116118
for key in old_basic:
117119
if key in EntariConfig.instance.basic and old_basic[key] != EntariConfig.instance.basic[key]:
118-
logger(
119-
"DEBUG",
120+
logger.opt(colors=True).debug(
120121
f"Basic config <y>{key!r}</y> changed from <r>{old_basic[key]!r}</r> "
121122
f"to <g>{EntariConfig.instance.basic[key]!r}</g>",
122123
)
123124
await es.publish(ConfigReload("basic", key, EntariConfig.instance.basic[key], old_basic[key]))
124125
for key in set(EntariConfig.instance.basic) - set(old_basic):
125-
logger("DEBUG", f"Basic config <y>{key!r}</y> appended")
126+
logger.opt(colors=True).debug(f"Basic config <y>{key!r}</y> appended")
126127
await es.publish(ConfigReload("basic", key, EntariConfig.instance.basic[key]))
127128
for plugin_name in old_plugin:
128129
if plugin_name.startswith("$") or plugin_name.startswith("~"):
@@ -132,11 +133,10 @@ async def watch_config(self):
132133
if plugin := find_plugin(pid):
133134
del plugin
134135
unload_plugin(pid)
135-
logger("INFO", f"Disposed plugin <blue>{pid!r}</blue>")
136+
logger.opt(colors=True).info(f"Disposed plugin <blue>{pid!r}</blue>")
136137
continue
137138
if old_plugin[plugin_name] != EntariConfig.instance.plugin[plugin_name]:
138-
logger(
139-
"DEBUG",
139+
logger.opt(colors=True).debug(
140140
f"Plugin <y>{plugin_name!r}</y> config changed from <r>{old_plugin[plugin_name]!r}</r> "
141141
f"to <g>{EntariConfig.instance.plugin[plugin_name]!r}</g>",
142142
)
@@ -146,25 +146,27 @@ async def watch_config(self):
146146
allow, deny, only_filter = detect_filter_change(old_conf, new_conf)
147147
plugin.update_filter(allow, deny)
148148
if only_filter:
149-
logger("DEBUG", f"Plugin <y>{pid!r}</y> config only changed filter.")
149+
logger.opt(colors=True).debug(f"Plugin <y>{pid!r}</y> config only changed filter.")
150150
continue
151151
res = await es.post(
152152
ConfigReload("plugin", plugin_name, new_conf, old_conf),
153153
)
154154
if res and res.value:
155-
logger("DEBUG", f"Plugin <y>{pid!r}</y> config change handled by itself.")
155+
logger.opt(colors=True).debug(f"Plugin <y>{pid!r}</y> config change handled by itself.")
156156
continue
157-
logger("INFO", f"Detected config of <blue>{pid!r}</blue> changed, reloading...")
157+
logger.opt(colors=True).info(
158+
f"Detected config of <blue>{pid!r}</blue> changed, reloading..."
159+
)
158160
plugin_file = str(plugin.module.__file__)
159161
unload_plugin(plugin_name)
160162
if plugin := load_plugin(plugin_name, new_conf):
161-
logger("INFO", f"Reloaded <blue>{plugin.id!r}</blue>")
163+
logger.opt(colors=True).info(f"Reloaded <blue>{plugin.id!r}</blue>")
162164
del plugin
163165
else:
164-
logger("ERROR", f"Failed to reload <blue>{plugin_name!r}</blue>")
166+
logger.opt(colors=True).error(f"Failed to reload <blue>{plugin_name!r}</blue>")
165167
self.fail[plugin_file] = pid
166168
else:
167-
logger("INFO", f"Detected <blue>{pid!r}</blue> appended, loading...")
169+
logger.opt(colors=True).info(f"Detected <blue>{pid!r}</blue> appended, loading...")
168170
load_plugin(plugin_name, new_conf)
169171
if new := (set(EntariConfig.instance.plugin) - set(old_plugin)):
170172
for plugin_name in new:

arclet/entari/event/send.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,15 @@
88
from ..message import MessageChain
99

1010
if TYPE_CHECKING:
11-
from ..session import SatoriEvent, Session
11+
from ..session import Session
1212

1313

1414
@dataclass
1515
class SendRequest:
1616
account: Account
1717
channel: str
1818
message: MessageChain
19-
session: Union["Session[SatoriEvent]", None] = None
19+
session: Union["Session", None] = None
2020

2121
async def gather(self, context: Contexts):
2222
context["account"] = self.account
@@ -39,7 +39,7 @@ class SendResponse:
3939
channel: str
4040
message: MessageChain
4141
result: list[MessageReceipt]
42-
session: Union["Session[SatoriEvent]", None] = None
42+
session: Union["Session", None] = None
4343

4444
async def gather(self, context: Contexts):
4545
context["account"] = self.account

arclet/entari/logger.py

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,12 @@ def message(self):
3737
return self.loggers["[message]"]
3838

3939
def wrapper(self, name: str, color: str = "blue"):
40-
patched = logger.patch(lambda r: r.update(name="entari"))
40+
patched = logger.patch(
41+
lambda r: r.update(name="entari", extra={"entari_plugin_name": name, "entari_plugin_color": color})
42+
)
4143
patched = patched.bind(name=f"plugins.{name}")
4244
self.loggers[f"plugin.{name}"] = patched
43-
44-
def _log(level: str, message: str, exception: Exception | None = None):
45-
patched.opt(colors=True, exception=exception).log(level, f"| <{color}>{name}</{color}> {message}")
46-
47-
return _log
45+
return patched
4846

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

9290

91+
def _custom_format(record: Record):
92+
if "entari_plugin_name" in record["extra"]:
93+
plugin = (
94+
f" <{record['extra']['entari_plugin_color']}>"
95+
f"{record['extra']['entari_plugin_name']}"
96+
f"</{record['extra']['entari_plugin_color']}>"
97+
)
98+
else:
99+
plugin = ""
100+
return (
101+
f"<lk>{{time:YYYY-MM-DD HH:mm:ss}}</lk> <lvl>{{level}}</lvl> | <m><u>{{name}}</u></m>"
102+
f"{plugin} <lvl>{{message}}</lvl>\n"
103+
)
104+
105+
93106
logger.remove()
94107
logger_id = logger.add(
95108
sys.stdout,
@@ -98,7 +111,7 @@ def default_filter(record):
98111
backtrace=True,
99112
colorize=True,
100113
filter=default_filter,
101-
format="<lk>{time:YYYY-MM-DD HH:mm:ss}</lk> <lvl>{level:8}</lvl> | <m><u>{name}</u></m> <lvl>{message}</lvl>",
114+
format=_custom_format,
102115
)
103116
"""默认日志处理器 id"""
104117

example_plugin.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ async def show(session: Session):
7272
await session.send_message(f"Execute `echo 123` Result: {res}")
7373
return f"Data: {kept_data}"
7474

75-
TEST = 5
75+
TEST = 6
7676

7777
print([*Plugin.current()._scope.subscribers])
7878
print(Plugin.current().subplugins)

0 commit comments

Comments
 (0)