We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Bug: Logger 发起对象名一律为 nonebot
**描述问题：**
![image](https://user-images.githubusercontent.com/59906398/115154552-ff6c3500-a0ad-11eb-8cca-7bbb0b1cc9d6.png)
在 [v2.0.0a11](https://github.com/nonebot/nonebot2/tree/v2.0.0a11) 及更早版本中，通过在事件处理的文件或者包中调用 `loguru.logger` 其输出的日志之发起对象名为该文件或包之名称
![image](https://user-images.githubusercontent.com/59906398/115154578-2cb8e300-a0ae-11eb-94f0-93857c642110.png)
在 [v2.0.0a13.post1](https://github.com/nonebot/nonebot2/tree/v2.0.0a13.post1) 中，使用相同方式输出的日志，其发起对象名一律为 nonebot

**期望的结果**

日志之发起对象名为该文件或包之名称

**环境信息：**

 - OS: windows-latest
 - Python Version: 3.9.4
 - Nonebot Version: v2.0.0a13.post1

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `nonebot/log.py`
Content:
```
1 """
2 日志
3 ====
4 
5 NoneBot 使用 `loguru`_ 来记录日志信息。
6 
7 自定义 logger 请参考 `loguru`_ 文档。
8 
9 .. _loguru:
10     https://github.com/Delgan/loguru
11 """
12 
13 import sys
14 import logging
15 from typing import Union
16 
17 from loguru import logger as logger_
18 
19 # logger = logging.getLogger("nonebot")
20 logger = logger_
21 """
22 :说明:
23 
24   NoneBot 日志记录器对象。
25 
26 :默认信息:
27 
28   * 格式: ``[%(asctime)s %(name)s] %(levelname)s: %(message)s``
29   * 等级: ``DEBUG`` / ``INFO`` ，根据 config 配置改变
30   * 输出: 输出至 stdout
31 
32 :用法:
33 
34 .. code-block:: python
35 
36     from nonebot.log import logger
37 """
38 
39 # default_handler = logging.StreamHandler(sys.stdout)
40 # default_handler.setFormatter(
41 #     logging.Formatter("[%(asctime)s %(name)s] %(levelname)s: %(message)s"))
42 # logger.addHandler(default_handler)
43 
44 
45 class Filter:
46 
47     def __init__(self) -> None:
48         self.level: Union[int, str] = "DEBUG"
49 
50     def __call__(self, record):
51         record["name"] = record["name"].split(".")[0]
52         levelno = logger.level(self.level).no if isinstance(self.level,
53                                                             str) else self.level
54         return record["level"].no >= levelno
55 
56 
57 class LoguruHandler(logging.Handler):
58 
59     def emit(self, record):
60         try:
61             level = logger.level(record.levelname).name
62         except ValueError:
63             level = record.levelno
64 
65         frame, depth = logging.currentframe(), 2
66         while frame.f_code.co_filename == logging.__file__:
67             frame = frame.f_back
68             depth += 1
69 
70         logger.opt(depth=depth,
71                    exception=record.exc_info).log(level, record.getMessage())
72 
73 
74 logger.remove()
75 default_filter = Filter()
76 default_format = (
77     "<g>{time:MM-DD HH:mm:ss}</g> "
78     "[<lvl>{level}</lvl>] "
79     "<c><u>{name}</u></c> | "
80     # "<c>{function}:{line}</c>| "
81     "{message}")
82 logger_id = logger.add(sys.stdout,
83                        colorize=True,
84                        diagnose=False,
85                        filter=default_filter,
86                        format=default_format)
87
```

Path: `nonebot/plugin/manager.py`
Content:
```
1 import sys
2 import uuid
3 import pkgutil
4 import importlib
5 from hashlib import md5
6 from types import ModuleType
7 from collections import Counter
8 from contextvars import ContextVar
9 from importlib.abc import MetaPathFinder
10 from typing import Set, List, Optional, Iterable
11 from importlib.machinery import PathFinder, SourceFileLoader
12 
13 from .export import _export, Export
14 
15 _current_plugin: ContextVar[Optional[str]] = ContextVar("_current_plugin",
16                                                         default=None)
17 
18 _internal_space = ModuleType(__name__ + "._internal")
19 _internal_space.__path__ = []  # type: ignore
20 sys.modules[_internal_space.__name__] = _internal_space
21 
22 _manager_stack: List["PluginManager"] = []
23 
24 
25 class _NamespaceModule(ModuleType):
26     """Simple namespace module to store plugins."""
27 
28     @property
29     def __path__(self):
30         return []
31 
32     def __getattr__(self, name: str):
33         try:
34             return super().__getattr__(name)  # type: ignore
35         except AttributeError:
36             if name.startswith("__"):
37                 raise
38             raise RuntimeError("Plugin manager not activated!")
39 
40 
41 class _InternalModule(ModuleType):
42     """Internal module for each plugin manager."""
43 
44     def __init__(self, prefix: str, plugin_manager: "PluginManager"):
45         super().__init__(f"{prefix}.{plugin_manager.internal_id}")
46         self.__plugin_manager__ = plugin_manager
47 
48     @property
49     def __path__(self) -> List[str]:
50         return list(self.__plugin_manager__.search_path)
51 
52 
53 class PluginManager:
54 
55     def __init__(self,
56                  namespace: Optional[str] = None,
57                  plugins: Optional[Iterable[str]] = None,
58                  search_path: Optional[Iterable[str]] = None,
59                  *,
60                  id: Optional[str] = None):
61         self.namespace: Optional[str] = namespace
62         self.namespace_module: Optional[ModuleType] = self._setup_namespace(
63             namespace)
64 
65         self.id: str = id or str(uuid.uuid4())
66         self.internal_id: str = md5(
67             ((self.namespace or "") + self.id).encode()).hexdigest()
68         self.internal_module = self._setup_internal_module(self.internal_id)
69 
70         # simple plugin not in search path
71         self.plugins: Set[str] = set(plugins or [])
72         self.search_path: Set[str] = set(search_path or [])
73         # ensure can be loaded
74         self.list_plugins()
75 
76     def _setup_namespace(self,
77                          namespace: Optional[str] = None
78                         ) -> Optional[ModuleType]:
79         if not namespace:
80             return None
81 
82         try:
83             module = importlib.import_module(namespace)
84         except ImportError:
85             module = _NamespaceModule(namespace)
86             if "." in namespace:
87                 parent = importlib.import_module(namespace.rsplit(".", 1)[0])
88                 setattr(parent, namespace.rsplit(".", 1)[1], module)
89 
90         sys.modules[namespace] = module
91         return module
92 
93     def _setup_internal_module(self, internal_id: str) -> ModuleType:
94         if hasattr(_internal_space, internal_id):
95             raise RuntimeError("Plugin manager already exists!")
96 
97         prefix = sys._getframe(3).f_globals.get(
98             "__name__") or _internal_space.__name__
99         if not prefix.startswith(_internal_space.__name__):
100             prefix = _internal_space.__name__
101         module = _InternalModule(prefix, self)
102         sys.modules[module.__name__] = module
103         setattr(_internal_space, internal_id, module)
104         return module
105 
106     def __enter__(self):
107         if self in _manager_stack:
108             raise RuntimeError("Plugin manager already activated!")
109         _manager_stack.append(self)
110         return self
111 
112     def __exit__(self, exc_type, exc_value, traceback):
113         try:
114             _manager_stack.pop()
115         except IndexError:
116             pass
117 
118     def search_plugins(self) -> List[str]:
119         return [
120             module_info.name
121             for module_info in pkgutil.iter_modules(self.search_path)
122         ]
123 
124     def list_plugins(self) -> Set[str]:
125         _pre_managers: List[PluginManager]
126         if self in _manager_stack:
127             _pre_managers = _manager_stack[:_manager_stack.index(self)]
128         else:
129             _pre_managers = _manager_stack[:]
130 
131         _search_path: Set[str] = set()
132         for manager in _pre_managers:
133             _search_path |= manager.search_path
134         if _search_path & self.search_path:
135             raise RuntimeError("Duplicate plugin search path!")
136 
137         _search_plugins = self.search_plugins()
138         c = Counter([*_search_plugins, *self.plugins])
139         conflict = [name for name, num in c.items() if num > 1]
140         if conflict:
141             raise RuntimeError(
142                 f"More than one plugin named {' / '.join(conflict)}!")
143         return set(_search_plugins) | self.plugins
144 
145     def load_plugin(self, name) -> ModuleType:
146         if name in self.plugins:
147             with self:
148                 return importlib.import_module(name)
149 
150         if "." in name:
151             raise ValueError("Plugin name cannot contain '.'")
152 
153         with self:
154             return importlib.import_module(f"{self.namespace}.{name}")
155 
156     def load_all_plugins(self) -> List[ModuleType]:
157         return [self.load_plugin(name) for name in self.list_plugins()]
158 
159     def _rewrite_module_name(self, module_name) -> Optional[str]:
160         prefix = f"{self.internal_module.__name__}."
161         if module_name.startswith(self.namespace + "."):
162             path = module_name.split(".")
163             length = self.namespace.count(".") + 1
164             return f"{prefix}{'.'.join(path[length:])}"
165         elif module_name in self.plugins or module_name.startswith(prefix):
166             return module_name
167         elif module_name in self.search_plugins():
168             return f"{prefix}{module_name}"
169         return None
170 
171 
172 class PluginFinder(MetaPathFinder):
173 
174     def find_spec(self, fullname: str, path, target):
175         if _manager_stack:
176             index = -1
177             while -index <= len(_manager_stack):
178                 manager = _manager_stack[index]
179                 newname = manager._rewrite_module_name(fullname)
180                 if newname:
181                     spec = PathFinder.find_spec(
182                         newname, [*manager.search_path, *(path or sys.path)],
183                         target)
184                     if spec:
185                         spec.loader = PluginLoader(manager, newname,
186                                                    spec.origin)
187                         return spec
188                 index -= 1
189         return None
190 
191 
192 class PluginLoader(SourceFileLoader):
193 
194     def __init__(self, manager: PluginManager, fullname: str, path) -> None:
195         self.manager = manager
196         self.loaded = False
197         self._plugin_token = None
198         self._export_token = None
199         super().__init__(fullname, path)
200 
201     def create_module(self, spec) -> Optional[ModuleType]:
202         if self.name in sys.modules:
203             self.loaded = True
204             return sys.modules[self.name]
205         prefix = self.manager.internal_module.__name__
206         plugin_name = self.name[len(prefix):] if self.name.startswith(
207             prefix) else self.name
208         self._plugin_token = _current_plugin.set(plugin_name.lstrip("."))
209         self._export_token = _export.set(Export())
210         # return None to use default module creation
211         return super().create_module(spec)
212 
213     def exec_module(self, module: ModuleType) -> None:
214         if self.loaded:
215             return
216         # really need?
217         # setattr(module, "__manager__", self.manager)
218         if self._export_token:
219             setattr(module, "__export__", _export.get())
220 
221         super().exec_module(module)
222 
223         if self._plugin_token:
224             _current_plugin.reset(self._plugin_token)
225         if self._export_token:
226             _export.reset(self._export_token)
227         return
228 
229 
230 sys.meta_path.insert(0, PluginFinder())
231
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/nonebot/log.py b/nonebot/log.py
--- a/nonebot/log.py
+++ b/nonebot/log.py
@@ -47,6 +47,10 @@
         self.level = "DEBUG"
 
     def __call__(self, record):
+        module = sys.modules.get(record["name"])
+        if module:
+            plugin_name = getattr(module, "__plugin_name__", record["name"])
+            record["name"] = plugin_name
         record["name"] = record["name"].split(".")[0]
         levelno = logger.level(self.level).no
         return record["level"].no >= levelno
diff --git a/nonebot/plugin/manager.py b/nonebot/plugin/manager.py
--- a/nonebot/plugin/manager.py
+++ b/nonebot/plugin/manager.py
@@ -215,6 +215,9 @@
             return
         # really need?
         # setattr(module, "__manager__", self.manager)
+        if self._plugin_token:
+            setattr(module, "__plugin_name__",
+                    _current_plugin.get(self._plugin_token))
         if self._export_token:
             setattr(module, "__export__", _export.get())

{"golden_diff": "diff --git a/nonebot/log.py b/nonebot/log.py\n--- a/nonebot/log.py\n+++ b/nonebot/log.py\n@@ -47,6 +47,10 @@\n         self.level = \"DEBUG\"\n \n     def __call__(self, record):\n+        module = sys.modules.get(record[\"name\"])\n+        if module:\n+            plugin_name = getattr(module, \"__plugin_name__\", record[\"name\"])\n+            record[\"name\"] = plugin_name\n         record[\"name\"] = record[\"name\"].split(\".\")[0]\n         levelno = logger.level(self.level).no\n         return record[\"level\"].no >= levelno\ndiff --git a/nonebot/plugin/manager.py b/nonebot/plugin/manager.py\n--- a/nonebot/plugin/manager.py\n+++ b/nonebot/plugin/manager.py\n@@ -215,6 +215,9 @@\n             return\n         # really need?\n         # setattr(module, \"__manager__\", self.manager)\n+        if self._plugin_token:\n+            setattr(module, \"__plugin_name__\",\n+                    _current_plugin.get(self._plugin_token))\n         if self._export_token:\n             setattr(module, \"__export__\", _export.get())\n", "issue": "Bug: Logger \u53d1\u8d77\u5bf9\u8c61\u540d\u4e00\u5f8b\u4e3a nonebot\n**\u63cf\u8ff0\u95ee\u9898\uff1a**\r\n![image](https://user-images.githubusercontent.com/59906398/115154552-ff6c3500-a0ad-11eb-8cca-7bbb0b1cc9d6.png)\r\n\u5728 [v2.0.0a11](https://github.com/nonebot/nonebot2/tree/v2.0.0a11) \u53ca\u66f4\u65e9\u7248\u672c\u4e2d\uff0c\u901a\u8fc7\u5728\u4e8b\u4ef6\u5904\u7406\u7684\u6587\u4ef6\u6216\u8005\u5305\u4e2d\u8c03\u7528 `loguru.logger` \u5176\u8f93\u51fa\u7684\u65e5\u5fd7\u4e4b\u53d1\u8d77\u5bf9\u8c61\u540d\u4e3a\u8be5\u6587\u4ef6\u6216\u5305\u4e4b\u540d\u79f0\r\n![image](https://user-images.githubusercontent.com/59906398/115154578-2cb8e300-a0ae-11eb-94f0-93857c642110.png)\r\n\u5728 [v2.0.0a13.post1](https://github.com/nonebot/nonebot2/tree/v2.0.0a13.post1) \u4e2d\uff0c\u4f7f\u7528\u76f8\u540c\u65b9\u5f0f\u8f93\u51fa\u7684\u65e5\u5fd7\uff0c\u5176\u53d1\u8d77\u5bf9\u8c61\u540d\u4e00\u5f8b\u4e3a nonebot\r\n\r\n**\u671f\u671b\u7684\u7ed3\u679c**\r\n\r\n\u65e5\u5fd7\u4e4b\u53d1\u8d77\u5bf9\u8c61\u540d\u4e3a\u8be5\u6587\u4ef6\u6216\u5305\u4e4b\u540d\u79f0\r\n\r\n**\u73af\u5883\u4fe1\u606f\uff1a**\r\n\r\n - OS: windows-latest\r\n - Python Version: 3.9.4\r\n - Nonebot Version: v2.0.0a13.post1\n", "before_files": [{"content": "\"\"\"\n\u65e5\u5fd7\n====\n\nNoneBot \u4f7f\u7528 `loguru`_ \u6765\u8bb0\u5f55\u65e5\u5fd7\u4fe1\u606f\u3002\n\n\u81ea\u5b9a\u4e49 logger \u8bf7\u53c2\u8003 `loguru`_ \u6587\u6863\u3002\n\n.. _loguru:\n    https://github.com/Delgan/loguru\n\"\"\"\n\nimport sys\nimport logging\nfrom typing import Union\n\nfrom loguru import logger as logger_\n\n# logger = logging.getLogger(\"nonebot\")\nlogger = logger_\n\"\"\"\n:\u8bf4\u660e:\n\n  NoneBot \u65e5\u5fd7\u8bb0\u5f55\u5668\u5bf9\u8c61\u3002\n\n:\u9ed8\u8ba4\u4fe1\u606f:\n\n  * \u683c\u5f0f: ``[%(asctime)s %(name)s] %(levelname)s: %(message)s``\n  * \u7b49\u7ea7: ``DEBUG`` / ``INFO`` \uff0c\u6839\u636e config \u914d\u7f6e\u6539\u53d8\n  * \u8f93\u51fa: \u8f93\u51fa\u81f3 stdout\n\n:\u7528\u6cd5:\n\n.. code-block:: python\n\n    from nonebot.log import logger\n\"\"\"\n\n# default_handler = logging.StreamHandler(sys.stdout)\n# default_handler.setFormatter(\n#     logging.Formatter(\"[%(asctime)s %(name)s] %(levelname)s: %(message)s\"))\n# logger.addHandler(default_handler)\n\n\nclass Filter:\n\n    def __init__(self) -> None:\n        self.level: Union[int, str] = \"DEBUG\"\n\n    def __call__(self, record):\n        record[\"name\"] = record[\"name\"].split(\".\")[0]\n        levelno = logger.level(self.level).no if isinstance(self.level,\n                                                            str) else self.level\n        return record[\"level\"].no >= levelno\n\n\nclass LoguruHandler(logging.Handler):\n\n    def emit(self, record):\n        try:\n            level = logger.level(record.levelname).name\n        except ValueError:\n            level = record.levelno\n\n        frame, depth = logging.currentframe(), 2\n        while frame.f_code.co_filename == logging.__file__:\n            frame = frame.f_back\n            depth += 1\n\n        logger.opt(depth=depth,\n                   exception=record.exc_info).log(level, record.getMessage())\n\n\nlogger.remove()\ndefault_filter = Filter()\ndefault_format = (\n    \"<g>{time:MM-DD HH:mm:ss}</g> \"\n    \"[<lvl>{level}</lvl>] \"\n    \"<c><u>{name}</u></c> | \"\n    # \"<c>{function}:{line}</c>| \"\n    \"{message}\")\nlogger_id = logger.add(sys.stdout,\n                       colorize=True,\n                       diagnose=False,\n                       filter=default_filter,\n                       format=default_format)\n", "path": "nonebot/log.py"}, {"content": "import sys\nimport uuid\nimport pkgutil\nimport importlib\nfrom hashlib import md5\nfrom types import ModuleType\nfrom collections import Counter\nfrom contextvars import ContextVar\nfrom importlib.abc import MetaPathFinder\nfrom typing import Set, List, Optional, Iterable\nfrom importlib.machinery import PathFinder, SourceFileLoader\n\nfrom .export import _export, Export\n\n_current_plugin: ContextVar[Optional[str]] = ContextVar(\"_current_plugin\",\n                                                        default=None)\n\n_internal_space = ModuleType(__name__ + \"._internal\")\n_internal_space.__path__ = []  # type: ignore\nsys.modules[_internal_space.__name__] = _internal_space\n\n_manager_stack: List[\"PluginManager\"] = []\n\n\nclass _NamespaceModule(ModuleType):\n    \"\"\"Simple namespace module to store plugins.\"\"\"\n\n    @property\n    def __path__(self):\n        return []\n\n    def __getattr__(self, name: str):\n        try:\n            return super().__getattr__(name)  # type: ignore\n        except AttributeError:\n            if name.startswith(\"__\"):\n                raise\n            raise RuntimeError(\"Plugin manager not activated!\")\n\n\nclass _InternalModule(ModuleType):\n    \"\"\"Internal module for each plugin manager.\"\"\"\n\n    def __init__(self, prefix: str, plugin_manager: \"PluginManager\"):\n        super().__init__(f\"{prefix}.{plugin_manager.internal_id}\")\n        self.__plugin_manager__ = plugin_manager\n\n    @property\n    def __path__(self) -> List[str]:\n        return list(self.__plugin_manager__.search_path)\n\n\nclass PluginManager:\n\n    def __init__(self,\n                 namespace: Optional[str] = None,\n                 plugins: Optional[Iterable[str]] = None,\n                 search_path: Optional[Iterable[str]] = None,\n                 *,\n                 id: Optional[str] = None):\n        self.namespace: Optional[str] = namespace\n        self.namespace_module: Optional[ModuleType] = self._setup_namespace(\n            namespace)\n\n        self.id: str = id or str(uuid.uuid4())\n        self.internal_id: str = md5(\n            ((self.namespace or \"\") + self.id).encode()).hexdigest()\n        self.internal_module = self._setup_internal_module(self.internal_id)\n\n        # simple plugin not in search path\n        self.plugins: Set[str] = set(plugins or [])\n        self.search_path: Set[str] = set(search_path or [])\n        # ensure can be loaded\n        self.list_plugins()\n\n    def _setup_namespace(self,\n                         namespace: Optional[str] = None\n                        ) -> Optional[ModuleType]:\n        if not namespace:\n            return None\n\n        try:\n            module = importlib.import_module(namespace)\n        except ImportError:\n            module = _NamespaceModule(namespace)\n            if \".\" in namespace:\n                parent = importlib.import_module(namespace.rsplit(\".\", 1)[0])\n                setattr(parent, namespace.rsplit(\".\", 1)[1], module)\n\n        sys.modules[namespace] = module\n        return module\n\n    def _setup_internal_module(self, internal_id: str) -> ModuleType:\n        if hasattr(_internal_space, internal_id):\n            raise RuntimeError(\"Plugin manager already exists!\")\n\n        prefix = sys._getframe(3).f_globals.get(\n            \"__name__\") or _internal_space.__name__\n        if not prefix.startswith(_internal_space.__name__):\n            prefix = _internal_space.__name__\n        module = _InternalModule(prefix, self)\n        sys.modules[module.__name__] = module\n        setattr(_internal_space, internal_id, module)\n        return module\n\n    def __enter__(self):\n        if self in _manager_stack:\n            raise RuntimeError(\"Plugin manager already activated!\")\n        _manager_stack.append(self)\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        try:\n            _manager_stack.pop()\n        except IndexError:\n            pass\n\n    def search_plugins(self) -> List[str]:\n        return [\n            module_info.name\n            for module_info in pkgutil.iter_modules(self.search_path)\n        ]\n\n    def list_plugins(self) -> Set[str]:\n        _pre_managers: List[PluginManager]\n        if self in _manager_stack:\n            _pre_managers = _manager_stack[:_manager_stack.index(self)]\n        else:\n            _pre_managers = _manager_stack[:]\n\n        _search_path: Set[str] = set()\n        for manager in _pre_managers:\n            _search_path |= manager.search_path\n        if _search_path & self.search_path:\n            raise RuntimeError(\"Duplicate plugin search path!\")\n\n        _search_plugins = self.search_plugins()\n        c = Counter([*_search_plugins, *self.plugins])\n        conflict = [name for name, num in c.items() if num > 1]\n        if conflict:\n            raise RuntimeError(\n                f\"More than one plugin named {' / '.join(conflict)}!\")\n        return set(_search_plugins) | self.plugins\n\n    def load_plugin(self, name) -> ModuleType:\n        if name in self.plugins:\n            with self:\n                return importlib.import_module(name)\n\n        if \".\" in name:\n            raise ValueError(\"Plugin name cannot contain '.'\")\n\n        with self:\n            return importlib.import_module(f\"{self.namespace}.{name}\")\n\n    def load_all_plugins(self) -> List[ModuleType]:\n        return [self.load_plugin(name) for name in self.list_plugins()]\n\n    def _rewrite_module_name(self, module_name) -> Optional[str]:\n        prefix = f\"{self.internal_module.__name__}.\"\n        if module_name.startswith(self.namespace + \".\"):\n            path = module_name.split(\".\")\n            length = self.namespace.count(\".\") + 1\n            return f\"{prefix}{'.'.join(path[length:])}\"\n        elif module_name in self.plugins or module_name.startswith(prefix):\n            return module_name\n        elif module_name in self.search_plugins():\n            return f\"{prefix}{module_name}\"\n        return None\n\n\nclass PluginFinder(MetaPathFinder):\n\n    def find_spec(self, fullname: str, path, target):\n        if _manager_stack:\n            index = -1\n            while -index <= len(_manager_stack):\n                manager = _manager_stack[index]\n                newname = manager._rewrite_module_name(fullname)\n                if newname:\n                    spec = PathFinder.find_spec(\n                        newname, [*manager.search_path, *(path or sys.path)],\n                        target)\n                    if spec:\n                        spec.loader = PluginLoader(manager, newname,\n                                                   spec.origin)\n                        return spec\n                index -= 1\n        return None\n\n\nclass PluginLoader(SourceFileLoader):\n\n    def __init__(self, manager: PluginManager, fullname: str, path) -> None:\n        self.manager = manager\n        self.loaded = False\n        self._plugin_token = None\n        self._export_token = None\n        super().__init__(fullname, path)\n\n    def create_module(self, spec) -> Optional[ModuleType]:\n        if self.name in sys.modules:\n            self.loaded = True\n            return sys.modules[self.name]\n        prefix = self.manager.internal_module.__name__\n        plugin_name = self.name[len(prefix):] if self.name.startswith(\n            prefix) else self.name\n        self._plugin_token = _current_plugin.set(plugin_name.lstrip(\".\"))\n        self._export_token = _export.set(Export())\n        # return None to use default module creation\n        return super().create_module(spec)\n\n    def exec_module(self, module: ModuleType) -> None:\n        if self.loaded:\n            return\n        # really need?\n        # setattr(module, \"__manager__\", self.manager)\n        if self._export_token:\n            setattr(module, \"__export__\", _export.get())\n\n        super().exec_module(module)\n\n        if self._plugin_token:\n            _current_plugin.reset(self._plugin_token)\n        if self._export_token:\n            _export.reset(self._export_token)\n        return\n\n\nsys.meta_path.insert(0, PluginFinder())\n", "path": "nonebot/plugin/manager.py"}], "after_files": [{"content": "\"\"\"\n\u65e5\u5fd7\n====\n\nNoneBot \u4f7f\u7528 `loguru`_ \u6765\u8bb0\u5f55\u65e5\u5fd7\u4fe1\u606f\u3002\n\n\u81ea\u5b9a\u4e49 logger \u8bf7\u53c2\u8003 `loguru`_ \u6587\u6863\u3002\n\n.. _loguru:\n    https://github.com/Delgan/loguru\n\"\"\"\n\nimport sys\nimport logging\n\nfrom loguru import logger as logger_\n\n# logger = logging.getLogger(\"nonebot\")\nlogger = logger_\n\"\"\"\n:\u8bf4\u660e:\n\n  NoneBot \u65e5\u5fd7\u8bb0\u5f55\u5668\u5bf9\u8c61\u3002\n\n:\u9ed8\u8ba4\u4fe1\u606f:\n\n  * \u683c\u5f0f: ``[%(asctime)s %(name)s] %(levelname)s: %(message)s``\n  * \u7b49\u7ea7: ``DEBUG`` / ``INFO`` \uff0c\u6839\u636e config \u914d\u7f6e\u6539\u53d8\n  * \u8f93\u51fa: \u8f93\u51fa\u81f3 stdout\n\n:\u7528\u6cd5:\n\n.. code-block:: python\n\n    from nonebot.log import logger\n\"\"\"\n\n# default_handler = logging.StreamHandler(sys.stdout)\n# default_handler.setFormatter(\n#     logging.Formatter(\"[%(asctime)s %(name)s] %(levelname)s: %(message)s\"))\n# logger.addHandler(default_handler)\n\n\nclass Filter:\n\n    def __init__(self) -> None:\n        self.level = \"DEBUG\"\n\n    def __call__(self, record):\n        module = sys.modules.get(record[\"name\"])\n        if module:\n            plugin_name = getattr(module, \"__plugin_name__\", record[\"name\"])\n            record[\"name\"] = plugin_name\n        record[\"name\"] = record[\"name\"].split(\".\")[0]\n        levelno = logger.level(self.level).no\n        return record[\"level\"].no >= levelno\n\n\nclass LoguruHandler(logging.Handler):\n\n    def emit(self, record):\n        try:\n            level = logger.level(record.levelname).name\n        except ValueError:\n            level = record.levelno\n\n        frame, depth = logging.currentframe(), 2\n        while frame.f_code.co_filename == logging.__file__:\n            frame = frame.f_back\n            depth += 1\n\n        logger.opt(depth=depth,\n                   exception=record.exc_info).log(level, record.getMessage())\n\n\nlogger.remove()\ndefault_filter = Filter()\ndefault_format = (\n    \"<g>{time:MM-DD HH:mm:ss}</g> \"\n    \"[<lvl>{level}</lvl>] \"\n    \"<c><u>{name}</u></c> | \"\n    # \"<c>{function}:{line}</c>| \"\n    \"{message}\")\nlogger_id = logger.add(sys.stdout,\n                       colorize=True,\n                       diagnose=False,\n                       filter=default_filter,\n                       format=default_format)\n", "path": "nonebot/log.py"}, {"content": "import sys\nimport uuid\nimport pkgutil\nimport importlib\nfrom hashlib import md5\nfrom types import ModuleType\nfrom collections import Counter\nfrom contextvars import ContextVar\nfrom importlib.abc import MetaPathFinder\nfrom typing import Set, List, Optional, Iterable\nfrom importlib.machinery import PathFinder, SourceFileLoader\n\nfrom .export import _export, Export\n\n_current_plugin: ContextVar[Optional[str]] = ContextVar(\"_current_plugin\",\n                                                        default=None)\n\n_internal_space = ModuleType(__name__ + \"._internal\")\n_internal_space.__path__ = []  # type: ignore\nsys.modules[_internal_space.__name__] = _internal_space\n\n_manager_stack: List[\"PluginManager\"] = []\n\n\nclass _NamespaceModule(ModuleType):\n    \"\"\"Simple namespace module to store plugins.\"\"\"\n\n    @property\n    def __path__(self):\n        return []\n\n    def __getattr__(self, name: str):\n        try:\n            return super().__getattr__(name)  # type: ignore\n        except AttributeError:\n            if name.startswith(\"__\"):\n                raise\n            raise RuntimeError(\"Plugin manager not activated!\")\n\n\nclass _InternalModule(ModuleType):\n    \"\"\"Internal module for each plugin manager.\"\"\"\n\n    def __init__(self, prefix: str, plugin_manager: \"PluginManager\"):\n        super().__init__(f\"{prefix}.{plugin_manager.internal_id}\")\n        self.__plugin_manager__ = plugin_manager\n\n    @property\n    def __path__(self) -> List[str]:\n        return list(self.__plugin_manager__.search_path)\n\n\nclass PluginManager:\n\n    def __init__(self,\n                 namespace: Optional[str] = None,\n                 plugins: Optional[Iterable[str]] = None,\n                 search_path: Optional[Iterable[str]] = None,\n                 *,\n                 id: Optional[str] = None):\n        self.namespace: Optional[str] = namespace\n        self.namespace_module: Optional[ModuleType] = self._setup_namespace(\n            namespace)\n\n        self.id: str = id or str(uuid.uuid4())\n        self.internal_id: str = md5(\n            ((self.namespace or \"\") + self.id).encode()).hexdigest()\n        self.internal_module = self._setup_internal_module(self.internal_id)\n\n        # simple plugin not in search path\n        self.plugins: Set[str] = set(plugins or [])\n        self.search_path: Set[str] = set(search_path or [])\n        # ensure can be loaded\n        self.list_plugins()\n\n    def _setup_namespace(self,\n                         namespace: Optional[str] = None\n                        ) -> Optional[ModuleType]:\n        if not namespace:\n            return None\n\n        try:\n            module = importlib.import_module(namespace)\n        except ImportError:\n            module = _NamespaceModule(namespace)\n            if \".\" in namespace:\n                parent = importlib.import_module(namespace.rsplit(\".\", 1)[0])\n                setattr(parent, namespace.rsplit(\".\", 1)[1], module)\n\n        sys.modules[namespace] = module\n        return module\n\n    def _setup_internal_module(self, internal_id: str) -> ModuleType:\n        if hasattr(_internal_space, internal_id):\n            raise RuntimeError(\"Plugin manager already exists!\")\n\n        prefix = sys._getframe(3).f_globals.get(\n            \"__name__\") or _internal_space.__name__\n        if not prefix.startswith(_internal_space.__name__):\n            prefix = _internal_space.__name__\n        module = _InternalModule(prefix, self)\n        sys.modules[module.__name__] = module\n        setattr(_internal_space, internal_id, module)\n        return module\n\n    def __enter__(self):\n        if self in _manager_stack:\n            raise RuntimeError(\"Plugin manager already activated!\")\n        _manager_stack.append(self)\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        try:\n            _manager_stack.pop()\n        except IndexError:\n            pass\n\n    def search_plugins(self) -> List[str]:\n        return [\n            module_info.name\n            for module_info in pkgutil.iter_modules(self.search_path)\n        ]\n\n    def list_plugins(self) -> Set[str]:\n        _pre_managers: List[PluginManager]\n        if self in _manager_stack:\n            _pre_managers = _manager_stack[:_manager_stack.index(self)]\n        else:\n            _pre_managers = _manager_stack[:]\n\n        _search_path: Set[str] = set()\n        for manager in _pre_managers:\n            _search_path |= manager.search_path\n        if _search_path & self.search_path:\n            raise RuntimeError(\"Duplicate plugin search path!\")\n\n        _search_plugins = self.search_plugins()\n        c = Counter([*_search_plugins, *self.plugins])\n        conflict = [name for name, num in c.items() if num > 1]\n        if conflict:\n            raise RuntimeError(\n                f\"More than one plugin named {' / '.join(conflict)}!\")\n        return set(_search_plugins) | self.plugins\n\n    def load_plugin(self, name) -> ModuleType:\n        if name in self.plugins:\n            with self:\n                return importlib.import_module(name)\n\n        if \".\" in name:\n            raise ValueError(\"Plugin name cannot contain '.'\")\n\n        with self:\n            return importlib.import_module(f\"{self.namespace}.{name}\")\n\n    def load_all_plugins(self) -> List[ModuleType]:\n        return [self.load_plugin(name) for name in self.list_plugins()]\n\n    def _rewrite_module_name(self, module_name) -> Optional[str]:\n        prefix = f\"{self.internal_module.__name__}.\"\n        if module_name.startswith(self.namespace + \".\"):\n            path = module_name.split(\".\")\n            length = self.namespace.count(\".\") + 1\n            return f\"{prefix}{'.'.join(path[length:])}\"\n        elif module_name in self.plugins or module_name.startswith(prefix):\n            return module_name\n        elif module_name in self.search_plugins():\n            return f\"{prefix}{module_name}\"\n        return None\n\n\nclass PluginFinder(MetaPathFinder):\n\n    def find_spec(self, fullname: str, path, target):\n        if _manager_stack:\n            index = -1\n            while -index <= len(_manager_stack):\n                manager = _manager_stack[index]\n                newname = manager._rewrite_module_name(fullname)\n                if newname:\n                    spec = PathFinder.find_spec(\n                        newname, [*manager.search_path, *(path or sys.path)],\n                        target)\n                    if spec:\n                        spec.loader = PluginLoader(manager, newname,\n                                                   spec.origin)\n                        return spec\n                index -= 1\n        return None\n\n\nclass PluginLoader(SourceFileLoader):\n\n    def __init__(self, manager: PluginManager, fullname: str, path) -> None:\n        self.manager = manager\n        self.loaded = False\n        self._plugin_token = None\n        self._export_token = None\n        super().__init__(fullname, path)\n\n    def create_module(self, spec) -> Optional[ModuleType]:\n        if self.name in sys.modules:\n            self.loaded = True\n            return sys.modules[self.name]\n        prefix = self.manager.internal_module.__name__\n        plugin_name = self.name[len(prefix):] if self.name.startswith(\n            prefix) else self.name\n        self._plugin_token = _current_plugin.set(plugin_name.lstrip(\".\"))\n        self._export_token = _export.set(Export())\n        # return None to use default module creation\n        return super().create_module(spec)\n\n    def exec_module(self, module: ModuleType) -> None:\n        if self.loaded:\n            return\n        # really need?\n        # setattr(module, \"__manager__\", self.manager)\n        if self._plugin_token:\n            setattr(module, \"__plugin_name__\",\n                    _current_plugin.get(self._plugin_token))\n        if self._export_token:\n            setattr(module, \"__export__\", _export.get())\n\n        super().exec_module(module)\n\n        if self._plugin_token:\n            _current_plugin.reset(self._plugin_token)\n        if self._export_token:\n            _export.reset(self._export_token)\n        return\n\n\nsys.meta_path.insert(0, PluginFinder())\n", "path": "nonebot/plugin/manager.py"}]}