Reputation: 6472
In some rare cases, I have to create a completely new trace, separate from any parent TraceContext or ObservationContext.
An example : I could have an api that starts the processing of 100 items, and let's say that for each of these items there will be feign calls, spring cloud stream hops, etc... Spring will automatically creates an ObservationContext from the api, so I will have the same trace for the api call and all the processing for each of these items. I'm using kibana, If I find an error log and filters on the traceId I get all the items, it's almost the same as no correlation at all, there are too many lines. I can't correlate on the spanId either, new spans are created all the time !
So in some specific and controlled cases I want to start a new trace for each of these items : I know I will loose the correlation with the api call, but that's OK.
I've played quite extensively with the ObservationRegistry, the ContextSnapshot, etc... but can't get it to working. The code always finds a way to find the parent ObservationContext of TracingContext.
Ideally I'd like to
This could be done quite easily before (with sleuth) ... but now it's a head scratcher :smile:
I don't know if this helps but I'm looking for the runWithNewTrace
method that would be used this way :
List<String> traceIds = new ArrayList<>();
Observation.createNotStarted("test.traceObservation", observationRegistry) // 1
.contextualName("create test with Observation API") // 2
.observe(() -> {
traceIds.add(getCurrentTraceId());
runWithNewTrace("test", () -> traceIds.add(getCurrentTraceId()));
traceIds.add(getCurrentTraceId());
});
String traceIdBefore = traceIds.get(0);
String traceIdThatShouldBeDifferent = traceIds.get(1);
String traceIdAfterThatShouldBeSameAsBefore = traceIds.get(2);
assertThat(traceIdThatShouldBeDifferent).isNotNull().isNotEqualTo("no-trace");
assertThat(traceIdBefore).isNotEqualTo(traceIdThatShouldBeDifferent);
assertThat(traceIdBefore).isEqualTo(traceIdAfterThatShouldBeSameAsBefore);
getTraceId looks like this :
public String getCurrentTraceId() {
Span currentSpan = tracer.currentSpan();
if (currentSpan != null && currentSpan.context() != null) {
return currentSpan.context().traceId();
}
return "no-trace";
}
Upvotes: 3
Views: 6905
Reputation: 6472
Got the answer from Marcin Grzejszczak : you have to use a NullObservation to clear all the thread stuff and create a new observation from there :
new NullObservation(observationRegistry)
.observe(() -> Observation.start(name, observationRegistry)
.observe(() -> {
// code to execute with a new observation
}));
Upvotes: 6