I am trying to capture a full end-to-end trace in Elastic APM using java agent 1.35.0.
I have got one Kafka producer application with Debezium under the hood that relies on the OpenTracing implementation. Therefore I had to register the ElasticAPMTracer to the GlobalTracer first:
GlobalTracer.registerIfAbsent(new ElasticApmTracer());
This producer application already publishes messages to my kafka endpoint with the expected header elasticapmtraceparent
. See also:
co.elastic.apm.agent.impl.transaction.TraceContext#TRACE_PARENT_BINARY_HEADER_NAME
This header is encoded from String to a Byte array and this is where things go wrong. Elastic expects certain parts to be encoded from a hex string to Binary and this is not the default behaviour as the serializer is not configured this way.
So, I came up with a solution to encode this in the expected format and my Kafka consumer applications (based on Spring Boot) are now using this header as their current trace id hence the full end-to-end trace is working.
However, I still don't understand that this has to be so complicated and isn't there a cleaner way then composing this trace id manually as such:
private void fillOutgoingTraceParentBinaryHeader(byte[] buffer, String traceParentHeader) {
if (traceParentHeader == null || traceParentHeader.length() < TEXT_HEADER_EXPECTED_LENGTH) {
log.warn("Trace parent header is null or does not have the minimal required length: {}", TEXT_HEADER_EXPECTED_LENGTH);
return;
}
if (buffer.length < 29) {
log.warn("Given byte array does not have the minimal required length - {}", 29);
return;
}
var traceParentHeaderArr = traceParentHeader.split(SPLIT_CHAR);
var traceId = hexStringToByteArray(traceParentHeaderArr[1]);
var parentId = hexStringToByteArray(traceParentHeaderArr[2]);
System.arraycopy(parentId, 0, buffer, 19, parentId.length);
buffer[0] = 0;
buffer[1] = 0;
System.arraycopy(traceId, 0, buffer, 2, traceId.length);
buffer[18] = 1;
System.arraycopy(parentId, 0, buffer, 19, parentId.length);
buffer[27] = 2;
buffer[28] = getNextByte(traceParentHeader, 53);
}
Happy to hear your thoughts on this topic.