AOP (aspect oriented programming) and logging. Is it really functional?
we are trying to implement Logging in our application using AOP (and PostSharp by the way but this question relates to any AOP framework).
The problem we are facing is that the information we get is like:
Entering method XXX with parameters:
This information is not very useful as normally what we get is the 3rd case. We are creating also LOTS of non useful information.
If you have used AOP for logging in any product how did you manage this problem?
Thanks in advance.
A few approaches:
Put a common interface on types that you want to log. (ILoggable, for example). Implementing that interface will give your aspect the ability to log exactly what you want. The downside is that you have to implement/maintain ILoggable for every object that you might log.
Use reflection (which is what I did in this audit example on my blog. It uses an MVC ActionFilter, but the principle is the same). The trade-offs are spelled out in the blog post, but basically it's complexity of using reflection and performance concerns, depending on how much you are logging and how often.
Use serialization. Given an object, serialize it to Json or XML or whatever, and log that string. Depending on what you're doing with the logs, this could range from perfect to worthless, and depending on how the serialization works and how complex the objects are, this could be a performance issue too.
I work on a new kind of AOP Framework to respond on the missing features of existing AOP Framework. You can find my open source project here : NConcern .NET AOP Framework
One of the differences with others is to allow you to develop your advice with System.Linq.Expression to avoid boxing/unboxing, reflection and hash jump based on type. It is a little harder to develop using Expression for beginner but easy for an advanced developer.
Example a simple example of logging (into console) without rewrite your business, reflection and boxing.
a business : Calculator
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
your logging Aspect implemented by linq expression to describe how Advice must work.
public class Logging : IAspect
{
//this is not an advice, this method is called to produce advices
public IEnumerable<IAdvice> Advise(MethodInfo method)
{
//generic presentation method
var presentation = typeof(Presentation). GetMethod("Of");
//example log on exception
//instance, arguments and exception are Expressions
yield return Advice.Linq.After.Throwing((instance, arguments, exception) =>
{
Expression.Call
(
typeof(Console).GetMethod("WriteLine",...),
Expression.Call
(
typeof(string).GetMethod("Concat", new Type[] { typeof(string[]) }),
Expression.NewArrayInit(typeof(string), arguments.Select(argument => argument.Type == typeof(string) ? argument : ...).ToArray())
)
)
}
}
}
链接地址: http://www.djcxy.com/p/17022.html
上一篇: 用附加模块重新编译Nginx