BAEL-5867: Micrometer Observability API with Spring Boot 3 (#13180)

* BAEL-5867: Create project and create first usage main method

* BAEL-5867: Use Observation API in Boot

* BAEL-5867: Refactoring and testing

* BAEL-5867: Add tracing

* BAEL-5867: Remove notes and add project as a module to the aggregator

* BAEL-5867: Fix pmd rules violation
This commit is contained in:
Ralf Ueberfuhr
2022-12-28 21:47:49 +01:00
committed by GitHub
parent ab892ba982
commit 40249f907c
16 changed files with 481 additions and 0 deletions
@@ -0,0 +1,13 @@
package com.baeldung.samples;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GreetingApplication {
public static void main(String[] args) {
SpringApplication.run(GreetingApplication.class, args);
}
}
@@ -0,0 +1,66 @@
package com.baeldung.samples;
import io.micrometer.core.instrument.Measurement;
import io.micrometer.core.instrument.Statistic;
import io.micrometer.core.instrument.observation.DefaultMeterObservationHandler;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
import io.micrometer.observation.ObservationTextPublisher;
import java.util.Optional;
import java.util.stream.StreamSupport;
public class SimpleObservationApplication {
// we can run this as a simple command line application
public static void main(String[] args) {
// create registry
final var observationRegistry = ObservationRegistry.create();
// create meter registry and observation handler
final var meterRegistry = new SimpleMeterRegistry();
final var meterObservationHandler = new DefaultMeterObservationHandler(meterRegistry);
// create simple logging observation handler
final var loggingObservationHandler = new ObservationTextPublisher(System.out::println);
// register observation handlers
observationRegistry
.observationConfig()
.observationHandler(meterObservationHandler)
.observationHandler(loggingObservationHandler);
// make an observation
Observation.Context context = new Observation.Context();
String observationName = "obs1";
Observation observation = Observation
.createNotStarted(observationName, () -> context, observationRegistry)
.lowCardinalityKeyValue("gender", "male")
.highCardinalityKeyValue("age", "41");
for (int i = 0; i < 10; i++) {
observation.observe(SimpleObservationApplication::doSomeAction);
}
meterRegistry.getMeters().forEach(m -> {
System.out.println(m.getId() + "\n============");
m.measure().forEach(ms -> System.out.println(ms.getValue() + " [" + ms.getStatistic() + "]"));
System.out.println("----------------------------");
});
Optional<Double> maximumDuration = meterRegistry.getMeters().stream()
.filter(m -> "obs1".equals(m.getId().getName()))
.flatMap(m -> StreamSupport.stream(m.measure().spliterator(), false))
.filter(ms -> ms.getStatistic() == Statistic.MAX)
.findFirst()
.map(Measurement::getValue);
System.out.println(maximumDuration);
}
private static void doSomeAction() {
try {
Thread.sleep(Math.round(Math.random() * 1000));
System.out.println("Hello World!");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,26 @@
package com.baeldung.samples.boundary;
import com.baeldung.samples.domain.GreetingService;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/greet")
public class GreetingController {
private final GreetingService service;
public GreetingController(GreetingService service) {
this.service = service;
}
@GetMapping(produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseBody
public String sayHello() {
return this.service.sayHello();
}
}
@@ -0,0 +1,22 @@
package com.baeldung.samples.boundary;
import io.micrometer.observation.ObservationRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.ServerHttpObservationFilter;
@Configuration
public class ObservationFilterConfiguration {
// if an ObservationRegistry is already configured
@ConditionalOnBean(ObservationRegistry.class)
// if we do not use Actuator
@ConditionalOnMissingBean(ServerHttpObservationFilter.class)
@Bean
public ServerHttpObservationFilter observationFilter(ObservationRegistry registry) {
return new ServerHttpObservationFilter(registry);
}
}
@@ -0,0 +1,28 @@
package com.baeldung.samples.config;
import io.micrometer.observation.ObservationHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class ObservationHandlerLogger {
private static final Logger log = LoggerFactory.getLogger(ObservationHandlerLogger.class);
private static String toString(ObservationHandler<?> handler) {
return handler.getClass().getName() + " [ " + handler + "]";
}
@EventListener(ContextRefreshedEvent.class)
public void logObservationHandlers(ContextRefreshedEvent evt) {
evt.getApplicationContext().getBeansOfType(ObservationHandler.class)
.values()
.stream()
.map(ObservationHandlerLogger::toString)
.forEach(log::info);
}
}
@@ -0,0 +1,21 @@
package com.baeldung.samples.config;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationHandler;
import io.micrometer.observation.ObservationTextPublisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ObservationTextPublisherConfiguration {
private static final Logger log = LoggerFactory.getLogger(ObservationTextPublisherConfiguration.class);
@Bean
public ObservationHandler<Observation.Context> observationTextPublisher() {
return new ObservationTextPublisher(log::info);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.samples.config;
import io.micrometer.observation.ObservationRegistry;
import io.micrometer.observation.aop.ObservedAspect;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
@AutoConfiguration
@ConditionalOnClass(ObservedAspect.class)
public class ObservedAspectConfiguration {
@Bean
@ConditionalOnMissingBean
public ObservedAspect observedAspect(ObservationRegistry observationRegistry) {
return new ObservedAspect(observationRegistry);
}
}
@@ -0,0 +1,59 @@
package com.baeldung.samples.config;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class SimpleLoggingHandler implements ObservationHandler<Observation.Context> {
private static final Logger log = LoggerFactory.getLogger(SimpleLoggingHandler.class);
private static String toString(Observation.Context context) {
return null == context ? "(no context)" : context.getName()
+ " (" + context.getClass().getName() + "@" + System.identityHashCode(context) + ")";
}
private static String toString(Observation.Event event) {
return null == event ? "(no event)" : event.getName();
}
@Override
public boolean supportsContext(Observation.Context context) {
return true;
}
@Override
public void onStart(Observation.Context context) {
log.info("Starting context " + toString(context));
}
@Override
public void onError(Observation.Context context) {
log.info("Error for context " + toString(context));
}
@Override
public void onEvent(Observation.Event event, Observation.Context context) {
log.info("Event for context " + toString(context) + " [" + toString(event) + "]");
}
@Override
public void onScopeOpened(Observation.Context context) {
log.info("Scope opened for context " + toString(context));
}
@Override
public void onScopeClosed(Observation.Context context) {
log.info("Scope closed for context " + toString(context));
}
@Override
public void onStop(Observation.Context context) {
log.info("Stopping context " + toString(context));
}
}
@@ -0,0 +1,14 @@
package com.baeldung.samples.domain;
import io.micrometer.observation.annotation.Observed;
import org.springframework.stereotype.Service;
@Observed(name = "greetingService")
@Service
public class GreetingService {
public String sayHello() {
return "Hello World!";
}
}
@@ -0,0 +1,6 @@
management:
endpoints:
web:
exposure:
include: '*'
#health,info,beans,metrics,startup