Monday, October 8, 2012

Using Spring AOP to profile application


  1. Create java class:


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;

public class MyProfiler
{
  Log
logger = LogFactory.getLog(getClass());
 
  public
MyProfiler () {
    this
.logger.info("Initialized");
  }
 
  public
Object methodResponseTime(ProceedingJoinPoint call) throws Throwable
  {
    Long startime = Long.valueOf(System.currentTimeMillis());
    try
{ Long responseTime;
      return
call.proceed();
    }
finally {
      Long responseTime = Long.valueOf(System.currentTimeMillis() - startime.longValue());
      this
.logger.info(String.valueOf(call.getSignature().toLongString()) + "::Response Time::" + responseTime);
    }
  }
}

 2. Spring context: create and configure spring to profile all methods in specified class

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

       <bean id="schedulerProfiler" class="X.X.MyProfiler" />

       <aop:config>
              <aop:aspect ref=" MyProfiler ">
             
                    
                     <!-- Business Layer -->   
                    
                     <aop:pointcut id="myBusinessResponseTimeLogger"
                           expression="execution(* com.X.business.myBusiness.*(..))" />
                          
                     <aop:around pointcut-ref="appointmentAdminBusinessResponseTimeLogger"
                           method="methodResponseTime" />

</aop:aspect>
       </aop:config>

</beans>

No comments:

Post a Comment