Search code examples
c#loggingpostsharp

PostSharp: Include some classes or some methods only


I need to add logging to a specific class or a specific method only. Reading documentation here and here I cannot find a way to reach my goal.

Listed below are my test cases.

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;
        }     

    }
}

AssemblyInfo content

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

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

In this way, I'm able to exclude the whole Class1 from the log, but only because it belongs to a different namespace.

How can I include Class3.Method2() only to the logging?


Solution

  • I post my solution using 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")]