Skip to content

Commit 8f1f099

Browse files
committed
refactor(sdk): 统一 SDK logger 入口,消除散落的 loguru 直接导入
新增 _internal/sdk_logger.py 作为 SDK 唯一日志出口,通过 logger.patch() 注入 plugin_tag、short_levelname、版本号等上下文字段,替换 12 个模块中 原有的 from loguru import logger 和 loader.py 里的 stdlib logging。 - decorator_lifecycle/cli/context/peer/supervisor/transport/worker/session_waiter/star: 改为从 sdk_logger 导入 - handler_dispatcher: 含方法内延迟导入也一并迁移 - loader: 移除 _LOGGER (logging.getLogger),全部改用 loguru + {} 格式串 - test_sdk_plugin_config_bridge: caplog 改为 monkeypatch 适配 loguru
1 parent d036b16 commit 8f1f099

14 files changed

Lines changed: 96 additions & 50 deletions

File tree

astrbot-sdk/src/astrbot_sdk/_internal/decorator_lifecycle.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from dataclasses import dataclass, field
77
from typing import Any
88

9-
from loguru import logger
109
from pydantic import ValidationError
1110

1211
from ..context import Context as RuntimeContext
@@ -23,6 +22,7 @@
2322
get_validate_config_meta,
2423
)
2524
from ..star import Star
25+
from .sdk_logger import logger
2626
from .star_runtime import bind_star_runtime
2727

2828
_RUNTIME_STATE_ATTR = "__astrbot_decorator_runtime_state__"
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from __future__ import annotations
2+
3+
import os
4+
5+
from loguru import logger as _raw_loguru_logger
6+
7+
try:
8+
from astrbot.core.config.default import VERSION as _ASTRBOT_VERSION
9+
except Exception: # noqa: BLE001
10+
_ASTRBOT_VERSION = ""
11+
12+
_SHORT_LEVEL_NAMES = {
13+
"DEBUG": "DBUG",
14+
"INFO": "INFO",
15+
"WARNING": "WARN",
16+
"ERROR": "ERRO",
17+
"CRITICAL": "CRIT",
18+
}
19+
20+
21+
def _get_short_level_name(level_name: str) -> str:
22+
return _SHORT_LEVEL_NAMES.get(level_name.upper(), level_name[:4].upper())
23+
24+
25+
def _build_source_file(pathname: str | None) -> str:
26+
if not pathname:
27+
return "unknown"
28+
dirname = os.path.dirname(pathname)
29+
return (
30+
os.path.basename(dirname) + "." + os.path.basename(pathname).replace(".py", "")
31+
)
32+
33+
34+
def _patch_record(record: dict) -> None:
35+
extra = record["extra"]
36+
extra.setdefault("plugin_tag", "[Core]")
37+
extra.setdefault("short_levelname", _get_short_level_name(record["level"].name))
38+
level_no = record["level"].no
39+
version_tag = (
40+
f" [v{_ASTRBOT_VERSION}]" if _ASTRBOT_VERSION and level_no >= 30 else ""
41+
)
42+
extra.setdefault("astrbot_version_tag", version_tag)
43+
extra.setdefault("source_file", _build_source_file(record["file"].path))
44+
extra.setdefault("source_line", record["line"])
45+
extra.setdefault("is_trace", False)
46+
47+
48+
logger = _raw_loguru_logger.patch(_patch_record)
49+
50+
__all__ = ["logger"]

astrbot-sdk/src/astrbot_sdk/cli.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@
3030
from typing import Any
3131

3232
import click
33-
from loguru import logger
3433

34+
from ._internal.sdk_logger import logger
3535
from .errors import AstrBotError
3636
from .runtime.bootstrap import run_plugin_worker, run_supervisor, run_websocket_server
3737
from .runtime.loader import load_plugin, load_plugin_spec, validate_plugin_spec

astrbot-sdk/src/astrbot_sdk/context.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,8 @@
3737
from pathlib import Path
3838
from typing import Any
3939

40-
from loguru import logger as base_logger
41-
4240
from ._internal.plugin_logger import PluginLogger
41+
from ._internal.sdk_logger import logger as base_logger
4342
from ._internal.star_runtime import current_star_instance
4443
from ._message_types import normalize_message_type
4544
from .clients import (

astrbot-sdk/src/astrbot_sdk/runtime/capability_dispatcher.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,9 @@
2121
from collections.abc import AsyncIterator, Sequence
2222
from typing import Any, cast, get_type_hints
2323

24-
from loguru import logger
25-
2624
from .._internal.invocation_context import caller_plugin_scope
2725
from .._internal.plugin_logger import PluginLogger
26+
from .._internal.sdk_logger import logger
2827
from .._internal.star_runtime import bind_star_runtime
2928
from .._internal.typing_utils import unwrap_optional
3029
from ..context import CancelToken, Context

astrbot-sdk/src/astrbot_sdk/runtime/handler_dispatcher.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,14 @@
2929
from dataclasses import dataclass
3030
from typing import Any, cast, get_type_hints
3131

32-
from loguru import logger
33-
3432
from .._internal.command_model import (
3533
parse_command_model_remainder,
3634
resolve_command_model_param,
3735
)
3836
from .._internal.injected_params import legacy_arg_parameter_names
3937
from .._internal.invocation_context import caller_plugin_scope
4038
from .._internal.plugin_logger import PluginLogger
39+
from .._internal.sdk_logger import logger
4140
from .._internal.star_runtime import bind_star_runtime
4241
from .._internal.typing_utils import unwrap_optional
4342
from ..clients.llm import LLMResponse
@@ -411,7 +410,7 @@ def _build_args(
411410
injected_payloads: _InjectedEventPayloads | None = None,
412411
) -> list[Any]:
413412
"""构建 handler 参数列表。"""
414-
from loguru import logger
413+
from .._internal.sdk_logger import logger
415414

416415
signature = inspect.signature(handler)
417416
injected_args: list[Any] = []

astrbot-sdk/src/astrbot_sdk/runtime/loader.py

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@
6060
import importlib.abc
6161
import inspect
6262
import json
63-
import logging
6463
import os
6564
import re
6665
import shutil
@@ -83,6 +82,7 @@
8382
plugin_capability_prefix,
8483
validate_plugin_id,
8584
)
85+
from .._internal.sdk_logger import logger
8686
from .._internal.typing_utils import unwrap_optional
8787
from ..decorators import (
8888
ConversationMeta,
@@ -119,7 +119,6 @@
119119
HandlerKind: TypeAlias = Literal["handler", "hook", "tool", "session"]
120120
DiscoverySeverity: TypeAlias = Literal["warning", "error"]
121121
DiscoveryPhase: TypeAlias = Literal["discovery", "load", "lifecycle", "reload"]
122-
_LOGGER = logging.getLogger(__name__)
123122
_PLUGIN_IMPORT_LOCK = threading.RLock()
124123
_VALID_HANDLER_KINDS: tuple[HandlerKind, ...] = ("handler", "hook", "tool", "session")
125124
_PLUGIN_PACKAGE_PREFIX = "astrbot_ext_"
@@ -413,8 +412,8 @@ def _build_param_specs(handler: Any) -> list[ParamSpec]:
413412
try:
414413
type_hints = typing.get_type_hints(handler)
415414
except Exception as exc:
416-
_LOGGER.warning(
417-
"Failed to resolve type hints for handler %s: %s",
415+
logger.warning(
416+
"Failed to resolve type hints for handler {}: {}",
418417
getattr(handler, "__qualname__", repr(handler)),
419418
exc,
420419
)
@@ -648,22 +647,22 @@ def load_plugin_config_schema(plugin: PluginSpec) -> dict[str, Any]:
648647
try:
649648
schema_payload = json.loads(schema_path.read_text(encoding="utf-8"))
650649
except json.JSONDecodeError as exc:
651-
_LOGGER.warning(
652-
"Failed to parse SDK plugin config schema %s: %s",
650+
logger.warning(
651+
"Failed to parse SDK plugin config schema {}: {}",
653652
schema_path,
654653
exc,
655654
)
656655
return {}
657656
except OSError as exc:
658-
_LOGGER.warning(
659-
"Failed to read SDK plugin config schema %s: %s",
657+
logger.warning(
658+
"Failed to read SDK plugin config schema {}: {}",
660659
schema_path,
661660
exc,
662661
)
663662
return {}
664663
if not isinstance(schema_payload, dict):
665-
_LOGGER.warning(
666-
"SDK plugin config schema %s must be a JSON object, got %s",
664+
logger.warning(
665+
"SDK plugin config schema {} must be a JSON object, got {}",
667666
schema_path,
668667
type(schema_payload).__name__,
669668
)
@@ -716,15 +715,15 @@ def load_plugin_config(
716715
else {}
717716
)
718717
except json.JSONDecodeError as exc:
719-
_LOGGER.warning(
720-
"Failed to parse SDK plugin config %s: %s",
718+
logger.warning(
719+
"Failed to parse SDK plugin config {}: {}",
721720
config_path,
722721
exc,
723722
)
724723
existing_payload = {}
725724
except OSError as exc:
726-
_LOGGER.warning(
727-
"Failed to read SDK plugin config %s: %s",
725+
logger.warning(
726+
"Failed to read SDK plugin config {}: {}",
728727
config_path,
729728
exc,
730729
)
@@ -1016,14 +1015,12 @@ def _load_state(state_path: Path) -> dict[str, Any]:
10161015
try:
10171016
data = json.loads(state_path.read_text(encoding="utf-8"))
10181017
except json.JSONDecodeError as exc:
1019-
_LOGGER.warning(
1020-
"Failed to parse plugin worker state %s: %s", state_path, exc
1018+
logger.warning(
1019+
"Failed to parse plugin worker state {}: {}", state_path, exc
10211020
)
10221021
return {}
10231022
except OSError as exc:
1024-
_LOGGER.warning(
1025-
"Failed to read plugin worker state %s: %s", state_path, exc
1026-
)
1023+
logger.warning("Failed to read plugin worker state {}: {}", state_path, exc)
10271024
return {}
10281025
return data if isinstance(data, dict) else {}
10291026

@@ -1114,8 +1111,8 @@ def _load_component_instance(
11141111
f"{_component_context(plugin, class_path=resolved_component.class_path, index=resolved_component.index)} "
11151112
f"实例化失败:{exc}"
11161113
) from exc
1117-
_LOGGER.debug(
1118-
"Instantiated SDK plugin component %s for plugin %s",
1114+
logger.debug(
1115+
"Instantiated SDK plugin component {} for plugin {}",
11191116
resolved_component.class_path,
11201117
plugin.name,
11211118
)
@@ -1263,7 +1260,7 @@ def load_plugin(plugin: PluginSpec) -> LoadedPlugin:
12631260
仅支持 v4 新版 Star 组件(无参构造函数)。
12641261
"""
12651262
with _PLUGIN_IMPORT_LOCK:
1266-
_LOGGER.debug("Loading SDK plugin %s from %s", plugin.name, plugin.plugin_dir)
1263+
logger.debug("Loading SDK plugin {} from {}", plugin.name, plugin.plugin_dir)
12671264
_ensure_plugin_import_hook_installed()
12681265
namespace = _register_plugin_import_namespace(plugin)
12691266
_purge_plugin_bytecode(plugin.plugin_dir)
@@ -1304,8 +1301,8 @@ def load_plugin(plugin: PluginSpec) -> LoadedPlugin:
13041301
capabilities.extend(component_capabilities)
13051302
llm_tools.extend(component_tools)
13061303

1307-
_LOGGER.debug(
1308-
"Loaded SDK plugin %s: %d components, %d handlers, %d capabilities, %d llm tools, %d agents",
1304+
logger.debug(
1305+
"Loaded SDK plugin {}: {} components, {} handlers, {} capabilities, {} llm tools, {} agents",
13091306
plugin.name,
13101307
len(resolved_components),
13111308
len(handlers),

astrbot-sdk/src/astrbot_sdk/runtime/peer.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,11 @@
7373
from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
7474
from typing import Any
7575

76-
from loguru import logger
77-
7876
from .._internal.invocation_context import (
7977
caller_plugin_scope,
8078
current_caller_plugin_id,
8179
)
80+
from .._internal.sdk_logger import logger
8281
from ..context import CancelToken
8382
from ..errors import AstrBotError, ErrorCodes
8483
from ..protocol.messages import (

astrbot-sdk/src/astrbot_sdk/runtime/supervisor.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,11 @@
4343
from pathlib import Path
4444
from typing import IO, Any, cast
4545

46-
from loguru import logger
47-
4846
from .._internal.plugin_ids import (
4947
capability_belongs_to_plugin,
5048
plugin_capability_prefix,
5149
)
50+
from .._internal.sdk_logger import logger
5251
from ..errors import AstrBotError
5352
from ..protocol.descriptors import CapabilityDescriptor
5453
from ..protocol.messages import EventMessage, InitializeOutput, PeerInfo

astrbot-sdk/src/astrbot_sdk/runtime/transport.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
from collections.abc import Awaitable, Callable, Sequence
5757
from typing import IO, Any
5858

59-
from loguru import logger
59+
from .._internal.sdk_logger import logger
6060

6161
MessageHandler = Callable[[str], Awaitable[None]]
6262
STDIO_SUBPROCESS_STREAM_LIMIT = 8 * 1024 * 1024

0 commit comments

Comments
 (0)