1

I want to log exception for all of my methods using AOP. I had created an attribute for the same as following:

 [AttributeUsage(AttributeTargets.All)]
 public class ClsLogger : System.Attribute
 {
    private string _exMsg;
    public ClsLogger(string exMsg)
    {
        //
        // TODO: Add constructor logic here
        //
        _exMsg = exMsg;
        LogError();
    }
    public void LogError()
    {
        // This methods logs exception
        // Log Exception
    }
}

Finally, I want to use this logging attribute to log exception messages of the methods of my application. How I can pass exception messages to the atrribute as it is not a fixed string but varrible? Could anybody help on this?

user1672097
  • 361
  • 1
  • 4
  • 12

1 Answers1

1

Attributes in C# don't instantiate until you call GetCustomAttributes, and they instantiate every time you do so (see this question here on SO).

If you want to use AOP (as your title indicates), then you'll need to use some framework, like PostSharp, Fody, SheepAspect, etc.

If you are using ASP.NET MVC, then there is a built-in ActionFilter class that you can also use, but only on Controller methods.

Community
  • 1
  • 1
Matthew Groves
  • 25,181
  • 9
  • 71
  • 121