Last active
July 28, 2020 09:25
-
-
Save nhmarujo/9383ff12c00fc27d0c8703f31b326798 to your computer and use it in GitHub Desktop.
Aspect to hookup execution metrics to Spring Data Repositores
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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