首页 > 解决方案 > PostSharp:仅包含一些类或一些方法

问题描述

我只需要将日志记录添加到特定类或特定方法。在这里这里阅读文档我找不到实现目标的方法。

下面列出的是我的测试用例。

namespace ClassLibrary1.C1
{
    public class Class1
    {
        public int Method1()
        {
            return 42;
        }    
    } 
}

namespace ClassLibrary1.C2
{
    public class Class2
    {
        public int Method1()
        {
            return 42 * 2;
        }     
    }

    public class Class3
    {
        public int Method1()
        {
            return 42 * 2;
        }     

        public int Method2()
        {
            return 42 * 3;
        }     

    }
}

装配信息内容

using PostSharp.Patterns.Diagnostics;
using PostSharp.Extensibility;

[assembly: Log(AttributePriority = 1, AttributeExclude = true, AttributeTargetTypes = "ClassLibrary1.*")]
[assembly: Log(AttributePriority = 2, AttributeExclude = false, AttributeTargetTypes = "ClassLibrary1.C2*")]

通过这种方式,我能够从日志中排除整个 Class1,但这只是因为它属于不同的命名空间。

如何仅将Class3.Method2()包含到日志记录中?

标签: c#loggingpostsharp

解决方案


我使用 AttributeTargetMembers 发布我的解决方案

using PostSharp.Patterns.Diagnostics;
using PostSharp.Extensibility;

[assembly: Log(AttributePriority = 1, AttributeExclude = true, AttributeTargetMembers="Method1")]    
[assembly: Log(AttributePriority = 2, AttributeExclude = false, AttributeTargetMembers="Method2")]
[assembly: Log(AttributePriority = 3, AttributeExclude = true, AttributeTargetTypes = "ClassLibrary1.C1*")]
[assembly: Log(AttributePriority = 4, AttributeExclude = true, AttributeTargetTypes = "ClassLibrary1.C2.Class2")]

推荐阅读