The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor(feature_service): 将打印语句替换为结构化日志记录
XiaoYouChRbce5efdb28ae
diff --git a/app/services/feature_service.py b/app/services/feature_service.pyindex b347e17a..5fe64a81 100644--- a/app/services/feature_service.py+++ b/app/services/feature_service.py@@ -1,10 +1,11 @@import importlib.utilimport sysimport tomllib-import tracebackfrom pathlib import Pathfrom typing import TYPE_CHECKING, Dict, Any+from loguru import logger+from app.bases.interfaces import FeaturePackfrom app.bases.models import Task@@ -27,7 +28,7 @@ class FeatureService:featurePacks = []if not self.featuresPath.exists():- print(f"警告: features 文件夹不存在: {self.featuresPath}")+ logger.warning("features 文件夹不存在: {}", self.featuresPath)return featurePacksfor item in self.featuresPath.iterdir():@@ -52,28 +53,28 @@ class FeatureService:def _loadPackManifest(self, packDirectory: Path) -> dict[str, Any] | None:manifestPath = packDirectory / "manifest.toml"if not manifestPath.exists():- print(f"警告: FeaturePack 缺少 manifest.toml: {packDirectory}")+ logger.warning("FeaturePack 缺少 manifest.toml: {}", packDirectory)return Nonetry:manifest = tomllib.loads(manifestPath.read_text(encoding="utf-8"))except Exception as e:- print(f"警告: 无法读取 FeaturePack manifest {manifestPath}: {repr(e)}")+ logger.warning("无法读取 FeaturePack manifest {}: {}", manifestPath, repr(e))return NonepackConfig = manifest.get("pack")if not isinstance(packConfig, dict):- print(f"警告: FeaturePack manifest 缺少 [pack] 节: {manifestPath}")+ logger.warning("FeaturePack manifest 缺少 [pack] 节: {}", manifestPath)return Noneentry = packConfig.get("entry", "pack.py")if not isinstance(entry, str) or not entry.strip():- print(f"警告: FeaturePack manifest 的 entry 无效: {manifestPath}")+ logger.warning("FeaturePack manifest 的 entry 无效: {}", manifestPath)return NonepackPath = packDirectory / entryif not packPath.exists():- print(f"警告: FeaturePack 入口文件不存在: {packPath}")+ logger.warning("FeaturePack 入口文件不存在: {}", packPath)return Nonedependencies = packConfig.get("dependencies", [])@@ -81,7 +82,7 @@ class FeatureService:not isinstance(dependency, str) or not dependencyfor dependency in dependencies):- print(f"警告: FeaturePack manifest 的 dependencies 无效: {manifestPath}")+ logger.warning("FeaturePack manifest 的 dependencies 无效: {}", manifestPath)return Nonereturn {@@ -125,7 +126,7 @@ class FeatureService:except Exception as e:skipped.add(packName)visiting.clear()- print(f"[error] 跳过 FeaturePack {packName}: {e}")+ logger.error("跳过 FeaturePack {}: {}", packName, e)return [pack for pack in ordered if pack["name"] not in skipped]@@ -158,9 +159,7 @@ class FeatureService:try:cards.extend(packConfig.getDialogCards(parent))except Exception as e:- print(- f"[error] 获取 FeaturePack 对话框设置项失败 {packName}: {repr(e)}\n{traceback.format_exc()}"- )+ logger.opt(exception=e).error("获取 FeaturePack 对话框设置项失败 {}", packName)return cardsdef loadFeaturePack(@@ -181,7 +180,7 @@ class FeatureService:)if spec is None or spec.loader is None:- print(f"错误: 无法加载 feature pack: {packInfo['name']}")+ logger.error("无法加载 FeaturePack: {}", packInfo["name"])return Falsemodule = importlib.util.module_from_spec(spec)@@ -207,7 +206,7 @@ class FeatureService:breakif featurePackClass is None:- print(f"警告: 在 {packInfo['name']} 中未找到 FeaturePack 的子类")+ logger.warning("在 {} 中未找到 FeaturePack 子类", packInfo["name"])return FalsepackInstance = featurePackClass()@@ -223,15 +222,14 @@ class FeatureService:if refreshCache:self._refreshSortedPacksCache()- print(f"[ok] 成功加载 feature pack: {packInfo['name']}")+ logger.success("成功加载 FeaturePack: {}", packInfo["name"])return Trueexcept Exception as e:moduleName = packInfo["name"]if moduleName in sys.modules:del sys.modules[moduleName]- print(f"[error] 加载 feature pack 失败 {packInfo['name']}: {str(e)}")- traceback.print_exc()+ logger.opt(exception=e).error("加载 FeaturePack 失败 {}", packInfo["name"])return Falsedef getPackForUrl(self, url: str) -> tuple[str, FeaturePack] | tuple[None, None]:@@ -240,9 +238,7 @@ class FeatureService:if packInstance.canHandle(url):return packName, packInstanceexcept Exception as e:- print(- f"[error] FeaturePack.canHandle 失败 {packName}: {repr(e)}\n{traceback.format_exc()}"- )+ logger.opt(exception=e).error("FeaturePack.canHandle 失败 {}", packName)return None, Nonedef canHandle(self, url: str) -> bool:@@ -263,9 +259,7 @@ class FeatureService:if packInstance.canHandleTask(task):return packName, packInstanceexcept Exception as e:- print(- f"[error] FeaturePack.canHandleTask 失败 {packName}: {repr(e)}\n{traceback.format_exc()}"- )+ logger.opt(exception=e).error("FeaturePack.canHandleTask 失败 {}", packName)return None, Noneasync def parse(self, payload: dict) -> Task:@@ -303,22 +297,25 @@ class FeatureService:def loadFeatures(self, mainWindow: "MainWindow"):"""从 ./features 文件夹自动发现并加载所有 feature packs"""- print("开始加载 feature packs...")+ logger.info("开始加载 FeaturePacks")self.sortedPacksCache = []featurePacks = self.discoverFeaturePacks()if not featurePacks:- print("未发现任何 feature packs")+ logger.warning("未发现任何 FeaturePack")return- print(- f"发现 {len(featurePacks)} 个 feature packs: {[pack['name'] for pack in featurePacks]}"+ logger.info(+ "发现 {} 个 FeaturePack: {}",+ len(featurePacks),+ [pack["name"] for pack in featurePacks],)featurePacks = self._sortFeaturePacksByDependencies(featurePacks)- print(- f"FeaturePack 加载顺序: {[pack['name'] for pack in featurePacks]}"+ logger.info(+ "FeaturePack 加载顺序: {}",+ [pack["name"] for pack in featurePacks],)loadedCount = 0@@ -327,7 +324,11 @@ class FeatureService:loadedCount += 1self._refreshSortedPacksCache()- print(f"feature packs 加载完成: {loadedCount}/{len(featurePacks)} 个成功加载")+ if loadedCount == len(featurePacks):+ logger.success("FeaturePack 加载完成: {}/{} 个成功加载", loadedCount, len(featurePacks))+ return++ logger.warning("FeaturePack 加载完成: {}/{} 个成功加载", loadedCount, len(featurePacks))featureService = FeatureService()