tags:

views:

266

answers:

1

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) {...}
+1  A: 

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.

Saint Gerbil