开发者

using C# Custom Attributes for exception and audit trail logging

is it possible to create a custom feature that captures exceptions made in a method that are set by a 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 is: How do I capture the Method name where this attribute was placed and what event was thrown? It can ei开发者_开发问答ther capture an exception or just automatically log that this method was called.


This cannot be easily achieved. For example TypeMock uses the .NET framework profiler API to monitor an application's execution. It allows you to register for different events and be notified when a method is called, an exception occurs, ... but this is not going to be an easy task.

On the other hand you could use AOP but it requires you to modify your code so that the caller uses some generated proxy instead of the real class. Spring.NET has some nice features about it.

So basically without using the .NET framework Profiler API or without writing some custom code that reads those attributes from a given class using reflection you cannot achieve this. Attributes are just class metadata and without something that would make sense of them they do nothing.


Attributes are just metadata. You would need to do code-weaving, using something like PostSharp, or use a runtime interception library such as Castle.DynamicProxy. By themselves attributes contain no real functionality to the application except through reflection.

If you have a line of code inside the method that does the logging, you can get the stackframe of the calling method, use reflection to check for the attribute, and go from there. I am assuming 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.
    }
}


Have a look at

http://www.dcl.hpi.uni-potsdam.de/research/loom/rapier_loom.htm

http://www.dcl.hpi.uni-potsdam.de/research/loom/gripper_loom.htm

First is runtime weaver while second one is static weaver.

These are another good resources:

http://ayende.com/Blog/archive/2007/07/02/7-Approaches-for-AOP-in-.Net.aspx

http://msdn.microsoft.com/en-us/magazine/cc301356.aspx

http://www.codeproject.com/KB/architecture/AOP_Injection_IL.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜