Anyone has any idea on how to log method entries(including parameters value) and exit with Spring AOP and log4j at trace level. It should be able to log classes from multiple packages.
Asked
Active
Viewed 1.2k times
2 Answers
6
You can use @Around(..) aspect for such purposes:
@Component
@Aspect
@Order(value=2)
public class LoggingAspect {
@Around("execution(* com.blablabla.server..*.*(..))")
public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable{
final Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass().getName());
Object retVal = null;
try {
StringBuffer startMessageStringBuffer = new StringBuffer();
startMessageStringBuffer.append("Start method ");
startMessageStringBuffer.append(joinPoint.getSignature().getName());
startMessageStringBuffer.append("(");
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
startMessageStringBuffer.append(args[i]).append(",");
}
if (args.length > 0) {
startMessageStringBuffer.deleteCharAt(startMessageStringBuffer.length() - 1);
}
startMessageStringBuffer.append(")");
logger.trace(startMessageStringBuffer.toString());
StopWatch stopWatch = new StopWatch();
stopWatch.start();
retVal = joinPoint.proceed();
stopWatch.stop();
StringBuffer endMessageStringBuffer = new StringBuffer();
endMessageStringBuffer.append("Finish method ");
endMessageStringBuffer.append(joinPoint.getSignature().getName());
endMessageStringBuffer.append("(..); execution time: ");
endMessageStringBuffer.append(stopWatch.getTotalTimeMillis());
endMessageStringBuffer.append(" ms;");
logger.trace(endMessageStringBuffer.toString());
} catch (Throwable ex) {
StringBuffer errorMessageStringBuffer = new StringBuffer();
// Create error message with exception
logger.error(errorMessageStringBuffer.toString(), ex);
throw ex;
}
return retVal;
}
}
In this example around aspect logs all method calls for all subpackages under com.blablabla.server package. Also it logs all method input parameters.

Andre Hofmeister
- 3,185
- 11
- 51
- 74

dimas
- 6,033
- 36
- 29
1
You can use PerformanceMonitorInterceptor of Spring framework to log method entries.Here is the sample usage from DZone.

LeoColman
- 6,950
- 7
- 34
- 63

Sai Ye Yan Naing Aye
- 6,622
- 12
- 47
- 65