Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add arguments to PostSharp attributes?

Tags:

c#

postsharp

I have a simple PostSharp logging attribute:

[Serializable]
public class MethodLoggingAttribute : OnMethodBoundaryAspect
{
    private ILog _logger;
    public override void OnEntry(MethodExecutionEventArgs eventArgs)
    {
        _logger = LogManager.GetLogger(eventArgs.Method.DeclaringType.ToString());
        _logger.DebugFormat("Entered {0}", eventArgs.Method.Name);
    }
}

I want to make this attribute more flexible by adding information about the methods arguments to the log entry, but only if its needed.

[Serializable]
public class MethodLoggingAttribute : OnMethodBoundaryAspect
{
    private ILog _logger;
    public override void OnEntry(MethodExecutionEventArgs eventArgs)
    {
        _logger = LogManager.GetLogger(eventArgs.Method.DeclaringType.ToString());

        // if ShowParameters = true
        _logger.DebugFormat("Entered {0} with args:{1}", eventArgs.Method.Name, args);
        // else
        _logger.DebugFormat("Entered {0}", eventArgs.Method.Name);
        // endif
    }
}

The pseudo code with the IF is what I'm not sure how to do. How can I pass this into the attribute? I'm expecting it to look something like this but I don know how to handle it inside the attribute code:

[MethodLogging(ShowParameters=true)]
public void SomeCrazyMethod(int CustomerId, string SecretName) {...}
like image 780
Sailing Judo Avatar asked Apr 10 '09 14:04

Sailing Judo


1 Answers

Just declare a property

[Serializable]
public class MethodLoggingAttribute : OnMethodBoundaryAspect
{
    private ILog _logger;
    public override void OnEntry(MethodExecutionEventArgs eventArgs)
    {
        _logger = LogManager.GetLogger(eventArgs.Method.DeclaringType.ToString());
        if(ShowParameters = true)
        {
            _logger.DebugFormat("Entered {0} with args:{1}", eventArgs.Method.Name, args);
        }
        else
        {
            _logger.DebugFormat("Entered {0}", eventArgs.Method.Name);
        }
    }

    private bool m_ShowParameters;

    public bool ShowParameters
    {
        get { return m_ShowParameters; }
        set { m_ShowParameters = value; }
    }
}

Then you can specify it in the way you have mentioned.

like image 165
Mark Broadhurst Avatar answered Nov 12 '22 05:11

Mark Broadhurst