I am trying to use and extend spring boot’s Observation API solution for instrumenting metrics for spring mvc http.server.requests
.
I’m trying to add a custom tag, with the key duration
, and a value of http request execution time in ms. For this I have provided a @Bean
that extends DefaultServerRequestObservationConvention
from the org.springframework.http.server.observation
package like so:
public class ExtendedServerRequestObservationConvention extends DefaultServerRequestObservationConvention {
...
@Override
@NonNull
public KeyValues getHighCardinalityKeyValues(@NonNull ServerRequestObservationContext context) {
return super.getHighCardinalityKeyValues(context).and(addTag(context));
}
// additional tag that we want to include in the metrics
protected KeyValue addTag(ServerRequestObservationContext context) {
String requestDuration = context.get("duration");
assert requestDuration != null;
return KeyValue.of("duration", requestDuration);
}
}```
To measure the duration I’ve tried using the Timer
from the Observation.Context
and adding the value to the context with context.put()
, like so:
public class ExtendedObservationHandler implements ObservationHandler<ServerRequestObservationContext> {
...
@Override
public void onStop(ServerRequestObservationContext context) {
LongTaskTimer.Sample sample = context.get(LongTaskTimer.Sample.class);
if (sample != null) {
// Get the duration in the desired time unit, e.g., milliseconds
double duration = sample.duration(java.util.concurrent.TimeUnit.MILLISECONDS);
String durationStr = String.valueOf(duration);
System.out.println("Request duration: " + durationStr + "ms");
context.put("duration", durationStr);
}
ObservationHandler.super.onStop(context);
}
@Override
public boolean supportsContext(@NonNull Observation.Context context) {
return context instanceof ServerRequestObservationContext;
}
}
The problem is that the duration value is not available when I try to obtain it with context.get('duration')
in the ExtendedServerRequestObservationConvention
. I have both classes configured as @Bean
, they both work, but not ‘together’.
What am I missing? Can someone maybe help? Thank you!