From 79d3bbcdfea1868189ccf2c763c21e9e8dae77e2 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Mon, 19 Apr 2021 21:15:10 +0800 Subject: [PATCH] :loud_sound: change log level add level config --- docs/api/config.md | 24 ++++++++++++++++++++++++ nonebot/__init__.py | 12 +++++++----- nonebot/config.py | 22 ++++++++++++++++++++-- nonebot/log.py | 6 ++++-- nonebot/message.py | 2 +- nonebot/plugin/__init__.py | 2 +- pages/changelog.md | 6 +++++- tests/.env | 1 + tests/.env.dev | 1 + 9 files changed, 64 insertions(+), 12 deletions(-) diff --git a/docs/api/config.md b/docs/api/config.md index 654ea628..4b67620b 100644 --- a/docs/api/config.md +++ b/docs/api/config.md @@ -106,6 +106,30 @@ NoneBot 主要配置。大小写不敏感。 +### `log_level` + + +* **类型**: `Union[int, str]` + + +* **默认值**: `None` + + +* **说明** + + 配置 NoneBot 日志输出等级,可以为 `int` 类型等级或等级名称,参考 [loguru 日志等级](https://loguru.readthedocs.io/en/stable/api/logger.html#levels)。 + + + +* **示例** + + +```default +LOG_LEVEL=25 +LOG_LEVEL=INFO +``` + + ### `api_root` diff --git a/nonebot/__init__.py b/nonebot/__init__.py index aaf5ca77..df19fdbc 100644 --- a/nonebot/__init__.py +++ b/nonebot/__init__.py @@ -179,15 +179,17 @@ def init(*, _env_file: Optional[str] = None, **kwargs): """ global _driver if not _driver: - logger.info("NoneBot is initializing...") + logger.success("NoneBot is initializing...") env = Env() - logger.opt( - colors=True).info(f"Current Env: {env.environment}") config = Config(**kwargs, _common_config=env.dict(), _env_file=_env_file or f".env.{env.environment}") - default_filter.level = "DEBUG" if config.debug else "INFO" + default_filter.level = ( + "DEBUG" if config.debug else + "INFO") if config.log_level is None else config.log_level + logger.opt( + colors=True).info(f"Current Env: {env.environment}") logger.opt(colors=True).debug( f"Loaded Config: {escape_tag(str(config.dict()))}") @@ -223,7 +225,7 @@ def run(host: Optional[str] = None, nonebot.run(host="127.0.0.1", port=8080) """ - logger.info("Running NoneBot...") + logger.success("Running NoneBot...") get_driver().run(host, port, *args, **kwargs) diff --git a/nonebot/config.py b/nonebot/config.py index 26e832c5..ae82a3b6 100644 --- a/nonebot/config.py +++ b/nonebot/config.py @@ -15,10 +15,9 @@ NoneBot 使用 `pydantic`_ 以及 `python-dotenv`_ 来读取配置。 """ import os from pathlib import Path - from datetime import timedelta from ipaddress import IPv4Address -from typing import Any, Set, Dict, Tuple, Mapping, Optional +from typing import Any, Set, Dict, Union, Tuple, Mapping, Optional from pydantic import BaseSettings, IPvAnyAddress from pydantic.env_settings import SettingsError, InitSettingsSource, EnvSettingsSource @@ -173,6 +172,25 @@ class Config(BaseConfig): 是否以调试模式运行 NoneBot。 """ + log_level: Optional[Union[int, str]] = None + """ + - **类型**: ``Union[int, str]`` + - **默认值**: ``None`` + + :说明: + + 配置 NoneBot 日志输出等级,可以为 ``int`` 类型等级或等级名称,参考 `loguru 日志等级`_。 + + :示例: + + .. code-block:: default + + LOG_LEVEL=25 + LOG_LEVEL=INFO + + .. _loguru 日志等级: + https://loguru.readthedocs.io/en/stable/api/logger.html#levels + """ # bot connection configs api_root: Dict[str, str] = {} diff --git a/nonebot/log.py b/nonebot/log.py index 3f6d1e1a..4409162b 100644 --- a/nonebot/log.py +++ b/nonebot/log.py @@ -12,6 +12,7 @@ NoneBot 使用 `loguru`_ 来记录日志信息。 import sys import logging +from typing import Union from loguru import logger as logger_ @@ -44,11 +45,12 @@ logger = logger_ class Filter: def __init__(self) -> None: - self.level = "DEBUG" + self.level: Union[int, str] = "DEBUG" def __call__(self, record): record["name"] = record["name"].split(".")[0] - levelno = logger.level(self.level).no + levelno = logger.level(self.level).no if isinstance(self.level, + str) else self.level return record["level"].no >= levelno diff --git a/nonebot/message.py b/nonebot/message.py index 5b683cd1..4a3dc22c 100644 --- a/nonebot/message.py +++ b/nonebot/message.py @@ -199,7 +199,7 @@ async def handle_event(bot: "Bot", event: "Event") -> Optional[Exception]: except NoLogException: show_log = False if show_log: - logger.opt(colors=True).info(log_msg) + logger.opt(colors=True).success(log_msg) state = {} coros = list(map(lambda x: x(bot, event, state), _event_preprocessors)) diff --git a/nonebot/plugin/__init__.py b/nonebot/plugin/__init__.py index a8e1a2db..bf1d2827 100644 --- a/nonebot/plugin/__init__.py +++ b/nonebot/plugin/__init__.py @@ -946,7 +946,7 @@ def _load_plugin(manager: PluginManager, plugin_name: str) -> Optional[Plugin]: plugin = Plugin(plugin_name, module) plugins[plugin_name] = plugin logger.opt( - colors=True).info(f'Succeeded to import "{plugin_name}"') + colors=True).success(f'Succeeded to import "{plugin_name}"') return plugin except Exception as e: logger.opt(colors=True, exception=e).error( diff --git a/pages/changelog.md b/pages/changelog.md index 4315c502..ba36b2c6 100644 --- a/pages/changelog.md +++ b/pages/changelog.md @@ -4,7 +4,11 @@ sidebar: auto # 更新日志 -## v2.0.0a12 +## v2.0.0a14 + +- 修改日志等级,支持输出等级自定义 + +## v2.0.0a13.post1 - 分离 `handler` 与 `matcher` - 修复 `cqhttp` secret 校验出错 diff --git a/tests/.env b/tests/.env index c1b9dfb0..3f1ef917 100644 --- a/tests/.env +++ b/tests/.env @@ -1,3 +1,4 @@ ENVIRONMENT=dev +LOG_LEVEL=25 CUSTOM_CONFIG=common FASTAPI_RELOAD_DIRS=["test_plugins"] diff --git a/tests/.env.dev b/tests/.env.dev index 0d7d878f..27917583 100644 --- a/tests/.env.dev +++ b/tests/.env.dev @@ -2,6 +2,7 @@ DRIVER=nonebot.drivers.fastapi HOST=0.0.0.0 PORT=2333 DEBUG=true +# LOG_LEVEL=DEBUG SUPERUSERS=["123123123"] NICKNAME=["bot"]