Using custom C # attributes to log exception and audit logs

Is it possible to create a custom function that captures the exceptions made in the method that are set by the custom attribute?

im planning to do something like this:

[Logging(FeatureEnum.SomeFeature, IntentEnum.SomeIntent, "some comment")] public void SomeMethodThatDoesATask() { try { var doSomeAction = new LazyProcess(); doSomeAction.WhoDunnit(); } catch(Exception ex) { StaticMethodThatDoesLogging.CatchError(ex); } } 

Question: How to get the name of the method in which this attribute was placed, and which event was selected? It can either catch the exception, or simply automatically record that this method has been called.

+7
source share
3 answers

It's impossible. For example, TypeMock uses the .NET profiler API to monitor application execution. It allows you to register for different events and receive notification when a method is called, an exception occurs ... but this will not be an easy task.

On the other hand, you can use AOP, but you need to change your code so that the caller uses some kind of generated proxy instead of the real class. Spring.NET has some interesting features.

Thus, in principle, without using the .NET Framework Profiler API or writing code that reads these attributes from a given class using reflection, you cannot achieve this. Attributes are simply class metadata, and without anything that could understand them, they do nothing.

+5
source

Attributes are just metadata. You will need to do the programming using something like PostSharp or use a runtime capture library such as Castle.DynamicProxy. Attributes in themselves do not contain any real functionality for the application, except through reflection.

If you have a line of code inside a method that logs, you can get the stack frame of the calling method, use reflection to check the attribute, and go from there. I guess this is what you wanted to do with StaticMethodThatDoesLogging.

 public void CatchError(Exception ex) { StackFrame parentFrame = new StackFrame(1); MethodBase mi = parentFrame.GetMethod(); LoggingAttribute attr = mi.GetCustomAttributes(typeof(LoggingAttribute), true).FirstOrDefault() as LoggingAttribute; if (attr != null) { // do your logging. } } 
+1
source

All Articles