I am trying to inject a field in the MDC context using Context Reactor using Spring webflux. Reading documentation, its said that OpenTelemetry just puts the traceId and spanId in the MDC context but I need the parentId. I have tried to get the OpenTelemetry tracing context from Reactor(using the code below) but I dont get any. So I use "getOrDefault" to create a new one if it does not exist. I have put some fields in the OpenTelemetry Baggage but it seems that OpenTelemetry does not inject any baggage field from its context into MDC, just the traceId and spanId.
Is there a way to achieve this?. Is there some property like "otel.instrumentation.log-injection.baggage.enabled" to do it?.
Thanks.
import io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.api.baggage.BaggageBuilder;
import io.opentelemetry.context.Context;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
@Slf4j
@Component
public class ParentIdInjectionWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
var request = exchange.getRequest().getHeaders();
var spanId = request.getFirst("X-B3-SpanId");
return Mono.deferContextual(reactorCtx -> {
Context otelCtx = reactorCtx.getOrDefault(Context.class, Context.current());
// 1. Obtener el baggage existente (si hay)
Baggage oldBaggage = Baggage.fromContext(otelCtx);
// 2. Copiar el baggage antiguo y agregar la nueva entrada
BaggageBuilder baggageBuilder = Baggage.builder();
oldBaggage.forEach((key, value) -> baggageBuilder.put(key, value.getValue())); // Copiar entradas antiguas
baggageBuilder.put("parentId", spanId); // Agregar nueva entrada
Baggage mergedBaggage = baggageBuilder.build();
// 3. Establecer el baggage combinado en el contexto OTel
Context updatedOtelCtx = otelCtx.with(mergedBaggage);
// 4. Continuar la cadena con el contexto actualizado
return chain.filter(exchange).contextWrite(ctx -> ctx.put(Context.class, updatedOtelCtx));
});
}
}