| « TestDriven.NET update | Third drop of RubyCLR available » |
Measuring method call duration with Spring AOP
Here's one way of writing a reusable Spring advice which will measure and log the duration of all the calls to a given object (or to be more accurate, to the members of any interface it implements).
using System; using AopAlliance.Intercept; using log4net; using Spring.Aop.Framework;
public class ProfilingProxy : IMethodInterceptor { private static readonly ILog log = LogManager.GetLogger(typeof(ProfilingProxy));
public object Invoke(IMethodInvocation invocation) { DateTime startTime = DateTime.Now; try { return invocation.Proceed(); } finally { log.Info(string.Format("{0}.{1} call took {2}", invocation.Method.DeclaringType.Name, invocation.Method.Name, DateTime.Now - startTime)); } }
public static object GetProxy(object originalObject) { ProxyFactory factory = new ProxyFactory(originalObject); factory.AddAdvice(new ProfilingProxy()); return factory.GetProxy(); } }
Here in a real life use:
[Test, Explicit] public void BenchmarkLDAPCall() { BasicConfigurator.Configure(); ILDAPAuthenticationProvider provider = new DirectoryServicesAuthenticationProvider(); provider = (ILDAPAuthenticationProvider)BuildProfilingProxy(provider); Assert.IsTrue(provider.Authenticate("myldaphost", "cn=mylogin,o=mycompany"); }
As Bruno Baia pointed out, you may want to use a more accurate timer if the calls you want to measure have a short duration.
Why I like this approach: it's easy to reuse the profiling logic and you don't have to modify the profiled code (don't even need to have access to the code here). One drawback is that afaik, the profiled object has to implement an interface to let spring create the proxy.
That's all for today!
Feedback awaiting moderation
This post has 11 feedbacks awaiting moderation...