MDC.get("trace.id") always null in code

Hello,

I am using elk 8.15.x and apm-agent 1.52.1, and springboot 3.4.2.
apm-agent is in classpath and i use programmatically :

ElasticApmAttacher.attach();

I use ecs json output to a file and trace.id is present. No problem.
But i want to programmatically get trace.id in java code for two reasons :

  • inject trace id into sql comment (using hibernate's StatementInspector)
  • propagate trace id into sub threads for // processing. This processing is done on multiple Threads but is not async in the way that the parent request thread si waiting sub threads before responding.

For simplification purpose, i use this console pattern :

spring.logging.pattern.console: "%t - %X{trace.id:-null} - %m%n"

When I run this code from an incomming rest request :

@Slf4j
public class TraceIdStatementInspector implements StatementInspector {
    @Override
    public String inspect(String sql) {
        var traceId = MDC.get("trace.id");
        log.info("trace id from MCD programmatic call : {}", traceId);
        new Thread(() -> log.info("APM agent not propagating trace.id to child thread")).start();
        return String.format("-- trace.id=%s\n%s", traceId, sql);
    }
}

I got this result :

http-nio-8080-exec-1 - 6cf0cf0b34ca2ec0a0b58160e96ee61c - trace id from MCD programmatic call : null
Thread-14 - null - APM agent not propagating trace.id to child thread

We can see trace id has been generated and used by log pattern %X{trace.id} but cannot be used from within code by programmatically calling MDC. After debugging, i see that the apm-agent call MDC.put(trace.id) before each log() statement and then call MDC.remove(trace.id) after.

We also see that traceId is not propagated to child thread, wich seems normal. But I would like to use a custom spring TaskDecorator to propagate trace id programmatically.

My question : is it possible to get the current thread trace id generated by apm agent in some way ?

Thanks you.

getTraceId()
eg ElasticApm.currentSpan().getTraceId()

Thanks a lot Jack.
It was kind of a noob question sorry.
I searched into apm-agent-attach source code but now i understand, i had not added the apm-agent-api as a dependency of my project