Skip to content

Instantly share code, notes, and snippets.

@avvero
Created March 15, 2018 08:27
Show Gist options
  • Select an option

  • Save avvero/ea868b5754c73aef7302f28e41083868 to your computer and use it in GitHub Desktop.

Select an option

Save avvero/ea868b5754c73aef7302f28e41083868 to your computer and use it in GitHub Desktop.
add custom #metrics for #spring
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.actuate.metrics.GaugeService;
import org.springframework.stereotype.Component;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
@Slf4j
@Aspect
@Component
public class CustomMetricsCollector {
private static final String COUNTER_TEMPLATE = "counter.%s.%s";
private static final String GAUGE_TEMPLATE = "gauge.%s.%s";
@Autowired
private CounterService counterService;
@Autowired
private GaugeService gaugeService;
@Around("@annotation(com.fxclub.metrics.CollectMetrics)")
public Object collectMetrics(ProceedingJoinPoint pjp) throws Throwable {
String typeName = pjp.getSignature().getDeclaringTypeName();
String methodName = pjp.getSignature().getName();
counterService.increment(format(COUNTER_TEMPLATE, typeName, methodName));
long startTime = currentTimeMillis();
try {
return pjp.proceed();
} finally {
long elapsedTime = currentTimeMillis() - startTime;
gaugeService.submit(format(GAUGE_TEMPLATE, typeName, methodName), elapsedTime);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment