In last post and previous one I had shown how to setup AspectJ waving. There were also sample of simple method tracing. Here goes ultimate version:
package com.sample.utils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger; import org.slf4j.LoggerFactory;
@Aspect
public class MyLogger {
private static final Logger logger = LoggerFactory.getLogger(MyLogger.class);
public MyLogger() { }
@Before("execution(* com.klasses..*(..))")
public void logBefore(JoinPoint point) {
logger.trace(
"Autotrace entry {}.{}({})",
point.getSignature().getDeclaringTypeName(),
point.getSignature() .getName(),
point.getArgs()
);
}
@AfterReturning(pointcut = "execution(* com.klasses..*(..))", returning = "result")
public void logAfter(JoinPoint point, Object result) {
boolean hasReturnValue = true;
if (point.getSignature() instanceof MethodSignature) {
hasReturnValue = !((MethodSignature) point.getSignature()).getReturnType().getCanonicalName().equals("void");
}
if (hasReturnValue) {
logger.trace(
"Autotrace exit {}.{}({}) returned {}",
point.getSignature().getDeclaringTypeName(),
point .getSignature().getName(),
point.getArgs(),
result
);
} else {
logger.trace(
"Autotrace exit {}.{}({})",
point.getSignature().getDeclaringTypeName(),
point.getSignature() .getName(),
point.getArgs()
);
}
}
@AfterThrowing(pointcut = "execution(* com.klasses..*(..))", throwing = "error")
public void logThrow(JoinPoint point, Throwable error) {
logger.trace(
"Autotrace exit {}.{}({}) throwed {}",
point.getSignature().getDeclaringTypeName(),
point .getSignature().getName(),
point.getArgs(),
error
);
}
}