🔊 change log level add level config

This commit is contained in:
yanyongyu 2021-04-19 21:15:10 +08:00
parent c24d0def09
commit 79d3bbcdfe
9 changed files with 64 additions and 12 deletions

View File

@ -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`

View File

@ -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 <y><b>Env: {env.environment}</b></y>")
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 <y><b>Env: {env.environment}</b></y>")
logger.opt(colors=True).debug(
f"Loaded <y><b>Config</b></y>: {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)

View File

@ -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] = {}

View File

@ -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

View File

@ -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))

View File

@ -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 "<y>{plugin_name}</y>"')
colors=True).success(f'Succeeded to import "<y>{plugin_name}</y>"')
return plugin
except Exception as e:
logger.opt(colors=True, exception=e).error(

View File

@ -4,7 +4,11 @@ sidebar: auto
# 更新日志
## v2.0.0a12
## v2.0.0a14
- 修改日志等级,支持输出等级自定义
## v2.0.0a13.post1
- 分离 `handler``matcher`
- 修复 `cqhttp` secret 校验出错

View File

@ -1,3 +1,4 @@
ENVIRONMENT=dev
LOG_LEVEL=25
CUSTOM_CONFIG=common
FASTAPI_RELOAD_DIRS=["test_plugins"]

View File

@ -2,6 +2,7 @@ DRIVER=nonebot.drivers.fastapi
HOST=0.0.0.0
PORT=2333
DEBUG=true
# LOG_LEVEL=DEBUG
SUPERUSERS=["123123123"]
NICKNAME=["bot"]