Custom monitoring interceptor

PerformanceMonitorInterceptor is a very basic and simple way to monitor the execution of our method time. However, most of the time we would need more a controlled way to monitor the method and its parameters. For that, we can implement our custom interceptor, either by extending AbstractMonitoringInterceptor or writing around advice or a custom annotation. Here we will write a custom interceptor extending AbstractMonitoringInterceptor.

Let's extend the AbstractMonitoringInterceptor class and override the invokeUnderTrace method to log the start, end, and duration of a method. We can also log a warning if the method execution lasts more than 5 milliseconds. The following is the code sample for the custom monitoring interceptor:

public class CustomPerformanceMonitorInterceptor extends AbstractMonitoringInterceptor {

private static final long serialVersionUID = -4060921270422590121L;
public CustomPerformanceMonitorInterceptor() {
}

public CustomPerformanceMonitorInterceptor(boolean
useDynamicLogger) {
setUseDynamicLogger(useDynamicLogger);
}

@Override
protected Object invokeUnderTrace(MethodInvocation invocation, Log
log)
throws Throwable {
String name = createInvocationTraceName(invocation);
long start = System.currentTimeMillis();
log.info("Method " + name + " execution started at:" + new
Date());
try {
return invocation.proceed();
}
finally {
long end = System.currentTimeMillis();
long time = end - start;
log.info("Method "+name+" execution lasted:"+time+" ms");
log.info("Method "+name+" execution ended at:"+new Date());

if (time > 5){
log.warn("Method execution took longer than 5 ms!");
}
}
}
}

Every other step we saw in the basic PerformanceMonitorInterceptor would be same, just replace PerformanceMonitorInterceptor with CustomPerformanceMonitorInterceptor.

The following output is generated:

2018-02-07 22:23:44 INFO TransferServiceImpl:32 - Method com.packt.springhighperformance.ch03.bankingapp.service.TransferService.transfer execution lasted:5001 ms
2018-02-07 22:23:44 INFO TransferServiceImpl:33 - Method com.packt.springhighperformance.ch03.bankingapp.service.TransferService.transfer execution ended at:Wed Feb 07 22:23:44 EST 2018
2018-02-07 22:23:44 WARN TransferServiceImpl:36 - Method execution took longer than 5 ms!
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset