Skip to content

Instantly share code, notes, and snippets.

@avvero
Last active March 15, 2018 08:27
Show Gist options
  • Save avvero/52fb7653d5cd3a7e280481787f6ecc57 to your computer and use it in GitHub Desktop.
Save avvero/52fb7653d5cd3a7e280481787f6ecc57 to your computer and use it in GitHub Desktop.
add custom #metrics for #spring
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Slf4j
@Aspect
@Component
public class MetricsCollector {
@Autowired
private MetricRegistry metricRegistry;
@Around("@annotation(CollectMetrics)")
public Object collectMetrics(ProceedingJoinPoint pjp) throws Throwable {
String typeName = pjp.getSignature().getDeclaringTypeName();
String methodName = pjp.getSignature().getName();
// start timer
Timer.Context timer = metricRegistry.timer(MetricRegistry.name(typeName, methodName)).time();
//increment total requests meter
metricRegistry.meter(MetricRegistry.name(typeName, methodName)).mark();
try {
return pjp.proceed();
} finally {
timer.stop();
}
}
@AfterThrowing(value = "@annotation(CollectMetrics)", throwing = "e")
public void handleException(final JoinPoint jp, final Exception e){
String typeName = jp.getSignature().getDeclaringTypeName();
String methodName = jp.getSignature().getName();
metricRegistry.meter(MetricRegistry.name("error", typeName, methodName)).mark();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment