feat: 接入logger
This commit is contained in:
28
app/utils/__init__.py
Normal file
28
app/utils/__init__.py
Normal file
@@ -0,0 +1,28 @@
|
||||
# AUTO_MAA:A MAA Multi Account Management and Automation Tool
|
||||
# Copyright © 2024-2025 DLmaster361
|
||||
|
||||
# This file is part of AUTO_MAA.
|
||||
|
||||
# AUTO_MAA is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published
|
||||
# by the Free Software Foundation, either version 3 of the License,
|
||||
# or (at your option) any later version.
|
||||
|
||||
# AUTO_MAA is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty
|
||||
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
|
||||
# the GNU General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with AUTO_MAA. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# Contact: DLmaster_361@163.com
|
||||
|
||||
__version__ = "5.0.0"
|
||||
__author__ = "DLmaster361 <DLmaster_361@163.com>"
|
||||
__license__ = "GPL-3.0 license"
|
||||
|
||||
|
||||
from .logger import get_logger
|
||||
|
||||
__all__ = ["get_logger"]
|
||||
@@ -1,77 +0,0 @@
|
||||
'''
|
||||
配置文件管理, 使用yaml格式\n
|
||||
注意: 此文件仅处理程序配置项而非用户配置
|
||||
'''
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any, ClassVar
|
||||
import yaml
|
||||
from pydantic import BaseModel
|
||||
|
||||
class BaseYAMLConfig(BaseModel):
|
||||
# 必要项
|
||||
CONFIG_PATH: ClassVar[Path]
|
||||
|
||||
@classmethod
|
||||
def load(cls, config_path: Path | None = None) -> "BaseYAMLConfig":
|
||||
"""
|
||||
从 YAML 文件加载配置。如果文件不存在或为空,则使用类中定义的默认值。
|
||||
"""
|
||||
# 使用传入路径或类变量路径
|
||||
if not cls.CONFIG_PATH:
|
||||
raise ValueError("CONFIG_PATH必须被设置")
|
||||
path = (config_path or cls.CONFIG_PATH).resolve()
|
||||
|
||||
if not path.exists():
|
||||
# print(f"[Warning] Config file '{path}' not found. Using default values.")
|
||||
data: dict[str, Any] = {}
|
||||
else:
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
if data is None:
|
||||
data = {}
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError(f"Expected dict in {path}, got {type(data)}")
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Failed to load config from {path}: {e}")
|
||||
|
||||
try:
|
||||
return cls.model_validate(data)
|
||||
except Exception as e:
|
||||
raise ValueError(f"Invalid config for {cls.__name__}: {e}")
|
||||
|
||||
|
||||
class LogConfig (BaseModel):
|
||||
"""
|
||||
日志配置
|
||||
"""
|
||||
CONFIG_PATH:ClassVar[Path] = Path("config.yaml")
|
||||
|
||||
level: str = "DEBUG"
|
||||
writelevel: str = "INFO"
|
||||
log_dir: str = "logs"
|
||||
max_size: int = 10
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,45 +1,36 @@
|
||||
from loguru import logger as _logger
|
||||
import sys
|
||||
import os
|
||||
from app.utils.config import LogConfig
|
||||
from pathlib import Path
|
||||
|
||||
config = LogConfig()
|
||||
LOG_DIR = config.log_dir
|
||||
os.makedirs(LOG_DIR, exist_ok=True)
|
||||
(Path.cwd() / "debug").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
_logger.remove()
|
||||
|
||||
console_format = (
|
||||
"<green>{time:YYYY-MM-DD HH:mm:ss}</green>| "
|
||||
"<level>{level: <8}</level> | "
|
||||
"<yellow>{extra[module]}</yellow>- {message}"
|
||||
|
||||
_logger.add(
|
||||
sink=Path.cwd() / "debug/app.log",
|
||||
level="INFO",
|
||||
format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{extra[module]}</cyan> | <level>{message}</level>",
|
||||
enqueue=True,
|
||||
backtrace=True,
|
||||
diagnose=True,
|
||||
rotation="1 week",
|
||||
retention="1 month",
|
||||
compression="zip",
|
||||
)
|
||||
|
||||
_logger.add(
|
||||
sink=sys.stderr,
|
||||
format=console_format,
|
||||
level=config.level,
|
||||
level="DEBUG",
|
||||
format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{extra[module]}</cyan> | <level>{message}</level>",
|
||||
enqueue=True,
|
||||
backtrace=True,
|
||||
diagnose=True,
|
||||
colorize=True,
|
||||
enqueue=True,
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
file_format = "{time:YYYY-MM-DD HH:mm:ss}| {level: <8} | {extra[module]}- {message}"
|
||||
|
||||
_logger.add(
|
||||
sink=os.path.join(LOG_DIR, "app_{time:YYYY-MM-DD}.log"),
|
||||
format=file_format,
|
||||
level=config.writelevel,
|
||||
rotation="00:00",
|
||||
retention="7 days",
|
||||
colorize=False,
|
||||
encoding="utf-8",
|
||||
enqueue=True,
|
||||
)
|
||||
|
||||
_logger = _logger.patch(lambda record: record["extra"].setdefault("module", "未知模块"))
|
||||
|
||||
|
||||
@@ -53,18 +44,3 @@ def get_logger(module_name: str):
|
||||
|
||||
|
||||
__all__ = ["get_logger"]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger = get_logger("test1")
|
||||
logger.debug("调试信息(只在控制台显示)")
|
||||
logger.info("这是普通信息(控制台 + 文件)")
|
||||
logger.warning("这是警告")
|
||||
logger.error("发生错误")
|
||||
logger2 = get_logger("test2")
|
||||
logger2.error("发生错误")
|
||||
|
||||
try:
|
||||
_ = 1 / 0
|
||||
except Exception:
|
||||
logger.exception("捕获异常")
|
||||
|
||||
Reference in New Issue
Block a user