From 2db8a5d215b5b00b99aa4b00e5f874b9c6a5c55d Mon Sep 17 00:00:00 2001 From: GwWuYou <95328647+GeWuYou@users.noreply.github.com> Date: Tue, 23 Dec 2025 23:20:09 +0800 Subject: [PATCH] =?UTF-8?q?refactor(logging):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E7=94=9F=E6=88=90=E5=99=A8=E7=9A=84=E8=AF=AD?= =?UTF-8?q?=E6=B3=95=E5=88=86=E6=9E=90=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 使用 SyntaxProvider 替换原有的 candidates 遍历方式 - 实现更精确的语法节点匹配逻辑 - 添加对 [Log] 和 [Log(...)] 属性的完整支持 - 改进属性名称匹配,支持命名空间前缀 - 重构代码结构以提高性能和准确性 - 保持原有功能逻辑不变 --- .../generator/logging/LoggerGenerator.cs | 32 +++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/GFramework.Generator/generator/logging/LoggerGenerator.cs b/GFramework.Generator/generator/logging/LoggerGenerator.cs index 7347a98..b523d10 100644 --- a/GFramework.Generator/generator/logging/LoggerGenerator.cs +++ b/GFramework.Generator/generator/logging/LoggerGenerator.cs @@ -22,10 +22,26 @@ namespace GFramework.Generator.generator.logging /// 增量生成器初始化上下文 public void Initialize(IncrementalGeneratorInitializationContext context) { - // 查找所有类声明语法节点,并获取对应的符号信息 - var candidates = + // 筛选出带有指定属性标记的类 + var targets = context.SyntaxProvider.CreateSyntaxProvider( - static (node, _) => node is ClassDeclarationSyntax, + static (node, _) => + { + if (node is not ClassDeclarationSyntax cls) + return false; + + // 只要写了 [Log] / [Log(...)] 就命中 + return cls.AttributeLists + .SelectMany(a => a.Attributes) + .Any(a => + { + var name = a.Name.ToString(); + return name == "Log" + || name == "LogAttribute" + || name.EndsWith(".Log") + || name.EndsWith(".LogAttribute"); + }); + }, static (ctx, _) => { var classDecl = (ClassDeclarationSyntax)ctx.Node; @@ -34,16 +50,6 @@ namespace GFramework.Generator.generator.logging }) .Where(x => x.Symbol is not null); - // 筛选出带有指定属性标记的类 - var targets = - candidates.Where(x => - x.Symbol!.GetAttributes().Any(a => - { - var c = a.AttributeClass; - if (c is null) return false; - return c.ToDisplayString() == AttributeMetadataName - || c.Name == "LogAttribute"; - })); // 注册源代码输出,为符合条件的类生成日志相关的源代码 context.RegisterSourceOutput(targets, (spc, pair) =>