Step 1) Create your logger.
Code:
package com.earldouglas.aoplogging;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
@Component
@Aspect
public class MethodLogger {
@Around("execution(* com.earldouglas..*.*(..))")
public Object timeMethod(ProceedingJoinPoint joinPoint) throws Throwable {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object retVal = joinPoint.proceed();
stopWatch.stop();
StringBuffer logMessageStringBuffer = new StringBuffer();
logMessageStringBuffer.append(joinPoint.getTarget().getClass().getName());
logMessageStringBuffer.append(".");
logMessageStringBuffer.append(joinPoint.getSignature().getName());
logMessageStringBuffer.append("(");
logMessageStringBuffer.append(joinPoint.getArgs());
logMessageStringBuffer.append(")");
logMessageStringBuffer.append(" execution time: ");
logMessageStringBuffer.append(stopWatch.getTotalTimeMillis());
logMessageStringBuffer.append(" ms");
Logger.getLogger(this.getClass()).info(logMessageStringBuffer.toString());
return retVal;
}
}
Step 2) Set up your context.
Code:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<aop:aspectj-autoproxy />
<context:component-scan base-package="com.earldouglas.aoplogging" />
<bean class="com.earldouglas.greeter.DefaultGreeter" />
</beans>
Now any beans in com.earldouglas.* will have the @Around-annotated advice wired in to log their execution time.
In my example, I have an interface Greeter, with an implementation DefaultGreeter.