Home > Software engineering >  Migrating Sleuth to Observation API by Micrometar Spring Boot 3.0.0
Migrating Sleuth to Observation API by Micrometar Spring Boot 3.0.0

Time:12-09

We have Sleuth enabled on all endpoints Spring 2.7.x ( that comes out of the box). Just plain and simple traceId/spanId tracking. Now as in Spring Sleuth is no more available in Spring Boot 3.0.0. Is there a way to enable this new Observation Api on all endpoints.

Before had this:

/*
 List all beers in database
 */
public Mono<ServerResponse> listBeer() {
    return beerService.listBeers(null,  null, PageRequest.ofSize(50), true)
            .flatMap(beerDto -> ServerResponse.ok().bodyValue(beerDto))
            .switchIfEmpty(ServerResponse.notFound().build());


}

Now with new Api in every endpoint need to do this:

/*
 List all beers in database
 */
public Mono<ServerResponse> listBeer() {
    Observation observation = Observation.start("listBeer-sample", observationRegistry);
    return Mono.just(observation).flatMap(span -> {

                observation.scoped(() -> log.info("I can fetch trace id <TRACE:{}> ",
                        this.tracer.currentSpan().context().traceId())
                );
                return beerService.listBeers(null, null, PageRequest.ofSize(50), true)
                        .flatMap(beerDto -> ServerResponse.ok().bodyValue(beerDto))
                        .switchIfEmpty(ServerResponse.notFound().build());
            }).doFinally(signalType -> observation.stop())
            .contextWrite(context -> context.put(ObservationThreadLocalAccessor.KEY, observation));

}

}

Is there a way to enable traceId/spanId out of the box on all endpoints without all of this clutter?

CodePudding user response:

Based on your description, I think you want to integrate micrometar without changing the original code

Fortunately it can be implemented through @Observed aop

You can refer to the official documentation Refer to Section 4.6 observation

add config code

  @Bean
  public ObservedAspect observedAspect(ObservationRegistry observationRegistry) {
      return new ObservedAspect(observationRegistry, this::skipControllers);
  }
 
  private boolean skipControllers(ProceedingJoinPoint pjp) {
      Class<?> targetClass = pjp.getTarget().getClass();
      return targetClass.isAnnotationPresent(RestController.class) || targetClass.isAnnotationPresent(Controller.class);
  }

CodePudding user response:

Currently there's no other way but to be a little bit more verbose and use the tap or handle operator that will automatically put observations in scope. We will be working on better, automated solutions in the future

  • Related