Skip to content

Instantly share code, notes, and snippets.

@nhmarujo
Last active July 28, 2020 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nhmarujo/9383ff12c00fc27d0c8703f31b326798 to your computer and use it in GitHub Desktop.
Save nhmarujo/9383ff12c00fc27d0c8703f31b326798 to your computer and use it in GitHub Desktop.
Aspect to hookup execution metrics to Spring Data Repositores
@Aspect
@Component
public class SpringDataMetrics {
private static final Logger logger = LoggerFactory.getLogger(SpringDataMetrics.class);
private final MeterRegistry meterRegistry;
public SpringDataMetrics(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}
@Around("this(org.springframework.data.repository.Repository)")
public Object aroundRepositoryMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
StopWatch stopWatch = new StopWatch();
try {
stopWatch.start();
return proceedingJoinPoint.proceed();
} finally {
stopWatch.stop();
try {
Class<?> targetClass = AopUtils.getTargetClass(proceedingJoinPoint.getThis());
Class<?> repositoryClass = Arrays.stream(targetClass.getInterfaces())
.filter(Repository.class::isAssignableFrom)
.findFirst()
.orElse(proceedingJoinPoint.getSignature().getDeclaringType());
String type = Arrays.stream(repositoryClass.getInterfaces())
.filter(Repository.class::isAssignableFrom)
.findFirst()
.map(Class::getSimpleName)
.orElse("Unknown");
String repository = repositoryClass.getSimpleName();
String method = proceedingJoinPoint.getSignature().getName();
logger.debug(append("type", type)
.and(append("repository", repository))
.and(append("method", method)),
"Repository method executed");
Timer.builder("spring.data.methods")
.tag("type", type)
.tag("repository", repository)
.tag("method", method)
.register(meterRegistry)
.record(Duration.ofMillis(stopWatch.getTotalTimeMillis()));
} catch (Exception e) {
logger.error("Error recording spring data repository metrics", e);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment