Friday, February 22, 2013

Spring AOP Logging Example

In general, we print the input arguments and output response for debugging. If we add log statements in each methods, it is very troublesome, spring provides AOP make it easy.

1) add this configuration

<aop:aspectj-autoproxy />

2)


@Component
@Aspect
public class ServiceLoggingAspect extends ServiceBase {

@Around("execution(* com.abc.service.impl.*.*(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {

Long startTime = System.currentTimeMillis();
try {
Object result = joinPoint.proceed();
info("[" + joinPoint.getTarget().getClass().getName() + "]."
+ joinPoint.getSignature().getName(),
" return " + result + " with arguments : "
+ Arrays.toString(joinPoint.getArgs())
+ ", Time to execute : "
+ (System.currentTimeMillis() - startTime) + "ms");
return result;
} catch (Exception e) {
error("[" + joinPoint.getTarget().getClass().getName() + "]."
+ joinPoint.getSignature().getName(),
"Exception occured with arguments : "
+ Arrays.toString(joinPoint.getArgs())
+ ", Time to execute : "
+ (System.currentTimeMillis() - startTime) + "ms",
e);

throw e;
}
}
}

Take note: The runtime exception will not be printed, but checked exception will be printed.

No comments:

Post a Comment