Suppose you have Spring Boot actuator in your application, and you want to access metrics programmatically.
Or you want to gather a lot of system/application metrics initially.
After you enable the Spring Boot actuator in your application (https://www.baeldung.com/spring-boot-actuators), just autowire all actuator auto wire candidates:
@Autowired(required = false)
private MetricsEndpoint actuatorMetrics;
@Autowired(required = false)
private BeansEndpoint beansEndpoint;
@Autowired(required = false)
private EnvironmentEndpoint environmentEndpoint;
@Autowired(required = false)
private InfoEndpoint infoEndpoint;
@Autowired(required = false)
private ThreadDumpEndpoint threadDumpEndpoint;
@Autowired(required = false)
private MappingsEndpoint mappingsEndpoint;
You can use them like this:
private List<Object> collectSystemMetrics() {
List<Object> result = new ArrayList<>();
if (actuatorMetrics == null) {
result = Collections.singletonList("spring boot actuator is turned off. no system metrics available");
} else {
actuatorMetrics.listNames().getNames().stream()
.map(m -> actuatorMetrics.metric(m, null))
.forEach(result::add);
}
return result;
}
private List<Object> collectBeans() {
List<Object> result = new ArrayList<>();
if (beansEndpoint == null) {
result = Collections.singletonList("spring boot actuator is turned off. no beans info available");
} else {
result.add(beansEndpoint.beans().getContexts());
}
return result;
}
private List<Object> collectEnvironment() {
List<Object> result = new ArrayList<>();
if (environmentEndpoint == null) {
result = Collections.singletonList("spring boot actuator is turned off. no environment info available");
} else {
EnvironmentEndpoint.EnvironmentDescriptor ed = environmentEndpoint.environment(null);
result.add(Map.of("activeProfiles", ed.getActiveProfiles(), "propertySources", ed.getPropertySources()));
}
return result;
}
private List<Object> collectInfo() {
List<Object> result = new ArrayList<>();
if (infoEndpoint == null) {
result = Collections.singletonList("spring boot actuator is turned off. no info available");
} else {
result.add(infoEndpoint.info());
}
return result;
}
private List<Object> collectThreadDump() {
List<Object> result = new ArrayList<>();
if (threadDumpEndpoint == null) {
result = Collections.singletonList("spring boot actuator is turned off. no thread dump available");
} else {
result.add(threadDumpEndpoint.textThreadDump());
}
return result;
}
private List<Object> collectMappings() {
List<Object> result = new ArrayList<>();
if (mappingsEndpoint == null) {
result = Collections.singletonList("spring boot actuator is turned off. no mappings info available");
} else {
result.add(mappingsEndpoint.mappings());
}
return result;
}
That’s all.
If you still have any questions, feel free to ask me in the comments under this article, or write me on promark33@gmail.com.