nonebot2/nonebot/log.py

91 lines
2.2 KiB
Python
Raw Normal View History

2020-08-20 15:07:05 +08:00
"""
日志
====
2020-08-26 22:54:58 +08:00
NoneBot 使用 `loguru`_ 来记录日志信息
2020-08-20 15:07:05 +08:00
2020-08-26 22:54:58 +08:00
自定义 logger 请参考 `loguru`_ 文档
2020-08-20 15:07:05 +08:00
2020-08-26 22:54:58 +08:00
.. _loguru:
https://github.com/Delgan/loguru
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
from typing import Union
2020-06-30 10:13:58 +08:00
2020-08-26 22:54:58 +08:00
from loguru import logger as logger_
# logger = logging.getLogger("nonebot")
logger = logger_
2020-08-20 15:07:05 +08:00
"""
:说明:
NoneBot 日志记录器对象
:默认信息:
* 格式: ``[%(asctime)s %(name)s] %(levelname)s: %(message)s``
* 等级: ``DEBUG`` / ``INFO`` 根据 config 配置改变
* 输出: 输出至 stdout
:用法:
.. code-block:: python
from nonebot.log import logger
"""
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:
self.level: Union[int, str] = "DEBUG"
2020-08-27 13:27:42 +08:00
def __call__(self, record):
2021-04-19 21:40:27 +08:00
module = sys.modules.get(record["name"])
if module:
plugin_name = getattr(module, "__plugin_name__", record["name"])
record["name"] = plugin_name
2020-08-27 13:27:42 +08:00
record["name"] = record["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
class LoguruHandler(logging.Handler):
def emit(self, record):
try:
level = logger.level(record.levelname).name
except ValueError:
level = record.levelno
frame, depth = logging.currentframe(), 2
while frame.f_code.co_filename == logging.__file__:
frame = frame.f_back
depth += 1
logger.opt(depth=depth,
exception=record.exc_info).log(level, record.getMessage())
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}")
2021-03-19 00:24:38 +08:00
logger_id = logger.add(sys.stdout,
colorize=True,
diagnose=False,
filter=default_filter,
format=default_format)