nonebot2/nonebot/log.py

103 lines
2.5 KiB
Python
Raw Normal View History

2020-08-20 15:07:05 +08:00
"""
2022-01-12 19:24:01 +08:00
## 日志
2020-08-20 15:07:05 +08:00
NoneBot 使用 [`loguru`][loguru] 来记录日志信息
2020-08-20 15:07:05 +08:00
自定义 logger 请参考 [`loguru`][loguru] 文档
2020-08-20 15:07:05 +08:00
[loguru]: https://github.com/Delgan/loguru
2022-01-16 11:30:09 +08:00
FrontMatter:
sidebar_position: 7
description: nonebot.log 模块
2020-08-20 15:07:05 +08:00
"""
2020-06-30 10:13:58 +08:00
import sys
2020-08-27 13:27:42 +08:00
import logging
2021-09-27 00:19:30 +08:00
from typing import TYPE_CHECKING, Union
2020-06-30 10:13:58 +08:00
2021-05-21 15:15:04 +08:00
import loguru
2021-07-28 16:32:50 +08:00
if TYPE_CHECKING:
# avoid sphinx autodoc resolve annotation failed
# because loguru module do not have `Logger` class actually
from loguru import Logger
2020-08-26 22:54:58 +08:00
2022-01-14 12:32:03 +08:00
from nonebot.plugin import Plugin
2020-08-26 22:54:58 +08:00
# logger = logging.getLogger("nonebot")
2021-07-28 16:32:50 +08:00
logger: "Logger" = loguru.logger
2020-08-20 15:07:05 +08:00
"""
2022-01-12 18:16:05 +08:00
NoneBot 日志记录器对象
2020-08-20 15:07:05 +08:00
默认信息:
2020-08-20 15:07:05 +08:00
2022-01-16 11:30:09 +08:00
- 格式: `[%(asctime)s %(name)s] %(levelname)s: %(message)s`
- 等级: `INFO` 根据 `config.log_level` 配置改变
- 输出: 输出至 stdout
2020-08-20 15:07:05 +08:00
2022-01-12 18:53:30 +08:00
用法:
```python
2020-08-20 15:07:05 +08:00
from nonebot.log import logger
2022-01-12 18:53:30 +08:00
```
2020-08-20 15:07:05 +08:00
"""
2020-07-04 22:51:10 +08:00
2020-08-26 22:54:58 +08:00
# default_handler = logging.StreamHandler(sys.stdout)
# default_handler.setFormatter(
# logging.Formatter("[%(asctime)s %(name)s] %(levelname)s: %(message)s"))
# logger.addHandler(default_handler)
2020-08-27 13:27:42 +08:00
class Filter:
def __init__(self) -> None:
2021-12-28 15:19:53 +08:00
self.level: Union[int, str] = "INFO"
2020-08-27 13:27:42 +08:00
def __call__(self, record):
2021-07-03 11:50:56 +08:00
module_name: str = record["name"]
2022-01-14 12:32:03 +08:00
# TODO: get plugin name instead of module name
# module = sys.modules.get(module_name)
# if module and hasattr(module, "__plugin__"):
# plugin: "Plugin" = getattr(module, "__plugin__")
# module_name = plugin.module_name
2021-07-03 11:50:56 +08:00
record["name"] = module_name.split(".")[0]
levelno = (
logger.level(self.level).no if isinstance(self.level, str) else self.level
)
2020-08-27 13:27:42 +08:00
return record["level"].no >= levelno
2021-12-16 17:28:57 +08:00
class LoguruHandler(logging.Handler): # pragma: no cover
2020-08-27 13:27:42 +08:00
def emit(self, record):
try:
level = logger.level(record.levelname).name
except ValueError:
level = record.levelno
frame, depth = logging.currentframe(), 2
2021-07-03 11:50:56 +08:00
while frame and frame.f_code.co_filename == logging.__file__:
2020-08-27 13:27:42 +08:00
frame = frame.f_back
depth += 1
logger.opt(depth=depth, exception=record.exc_info).log(
level, record.getMessage()
)
2020-08-27 13:27:42 +08:00
2020-08-26 22:54:58 +08:00
logger.remove()
2020-08-27 13:27:42 +08:00
default_filter = Filter()
default_format = (
2020-08-27 16:43:58 +08:00
"<g>{time:MM-DD HH:mm:ss}</g> "
"[<lvl>{level}</lvl>] "
"<c><u>{name}</u></c> | "
2020-08-27 13:27:42 +08:00
# "<c>{function}:{line}</c>| "
"{message}"
)
logger_id = logger.add(
sys.stdout,
2021-12-28 14:33:03 +08:00
level=0,
colorize=True,
diagnose=False,
filter=default_filter,
format=default_format,
)