Wednesday, October 8, 2014

Springs (Profiling a method) using AOP.(logging the method execution time)

Dependencies:

pom.xml file add the below jar's:
          <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>

Creating the pro-filer :

package com.cscinfo.npadmin.aspect;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * @author kvennamp
 *
 */
@Aspect
public class BusinessProfiler {

private static final Logger logger = Logger.getLogger(BusinessProfiler.class);

@Pointcut("execution(* com.cscinfo.npadmin.service.impl.*.*(..))")
    public void serviceMethods() { }

    @Around("serviceMethods()")
    public Object profile(ProceedingJoinPoint pjp) throws Throwable {
            long start = System.currentTimeMillis();
            logger.info("Going to call the method "+pjp.getSignature().getName());
            Object output = pjp.proceed();
            logger.info(pjp.getSignature().getName()+"Method execution completed.");
            long elapsedTime = System.currentTimeMillis() - start;
            logger.info(pjp.getSignature().getName()+" Method execution time: " + elapsedTime + " milliseconds.");
            return output;
    }
}


In application context.xml file write

<aop:aspectj-autoproxy />
<bean id="businessProfiler" class="com.cscinfo.npadmin.aspect.BusinessProfiler"></bean>

Here all the services classes and method are inside the
com.cscinfo.npadmin.service.impl package.

The Above pro-filer will log the method name followed by how much time it took to process.

No comments: