GPQBot
1import logging2import sys3from typing import TYPE_CHECKING4
5from loguru import logger as _logger6
7from app.settings import settings8
9if TYPE_CHECKING: # To avoid circular import10from loguru import Logger11
12
13
14class InterceptHandler(logging.Handler):15def emit(self, record): # type: ignore16# Get corresponding Loguru level if it exists17try:18level = logger.level(record.levelname).name19except ValueError:20level = record.levelno21
22# Find caller from where originated the logged message23frame, depth = logging.currentframe(), 224while frame.f_code.co_filename == logging.__file__: # noqa: WPS352, WPS60925frame = frame.f_back # type: ignore [assignment]26depth += 127
28logger.opt(depth=depth, exception=record.exc_info).log(29level, record.getMessage()30)31
32
33def setup_logger() -> "Logger":34# Remove every logger's handlers and propagate to root logger35for name in logging.root.manager.loggerDict.keys():36logging.getLogger(name).handlers = []37logging.getLogger(name).propagate = True38
39# Intercept everything at the root logger40logging.basicConfig(handlers=[InterceptHandler()], level=0)41
42# Enable pybotx logger43_logger.enable("pybotx")44
45# Setup loguru main logger46_logger.configure(47handlers=[48{49"sink": sys.stdout,50"level": logging.DEBUG if settings.DEBUG else logging.INFO,51}52],53)54
55return _logger56
57
58logger = setup_logger()