I want to display traceId in logs for each request in Spring Cloud Gateway. However, traceId and spanId are just empty.
Log config is like below:
logging:
pattern:
level: "%5p [TRACE_ID: %X{traceId:-}] [SPAN_ID: %X{spanId:-}]"
Part of pom.xml:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-brave</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>3.0.1</version>
</dependency>
With Spring Boot 3.x and Micrometer 1.10+ you can try the following dependencies:
(Part of pom.xml)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-brave</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-observation</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<version>1.0.2</version>
<artifactId>micrometer-tracing</artifactId>
</dependency>
</dependencies>
And in the main class of the application make the following call:
import reactor.core.publisher.Hooks;
public static void main(String[] args) {
Hooks.enableAutomaticContextPropagation();
// ...
}
Spring Boot should soon integrate those versions of dependencies and make the call for you, but for now these manual steps should get you the logs with tracing info.
In reactor-core 3.5.3 we added automatic propagation of ThreadLocal values registered with context-propagation (optional) library which Micrometer also uses. For those interested in the details, check the PR introducing this feature. This is a general enhancement from what 3.5.0 brought, where the ThreadLocals were populated in special operators -> handle and tap (and its overloads).