Some of my microservices use log4j2 as logger. Spring cloud Sleuth has support for logback. How can I use Sleuth to get distributed tracing in this scenario. I understand to use sleuth with log4j2, I have to implement certain class. I tried this but no luck. Please help
-
1Any help here, stuck with same issue. Only possible solution seems is to integrate brave library directly – laughing buddha May 10 '20 at 18:03
3 Answers
Sleuth
puts the traceId and spanId in the MDC
(Mapped Diagnostic Context).
You can use %X
to check the MDC key value pairs, and Sleuth related keys are traceId
, spanId
, parentId
, spanExportable
.
To simulate the logback default style, just maunally add below snippet into your PatternLayout
:
[${APP_NAME},%X{traceId},%X{spanId},%X{spanExportable}]
${APP_NAME}
is just your spring:application:name
.

- 1,300
- 4
- 12
- 30
Please try with the latest 2.0.0.M6 release where we use Brave internally. You can check out the https://github.com/openzipkin/brave/tree/master/context/log4j12 module how to set up the logging mechanism properly.
In Spring Cloud Sleuth just create a bean like this:
@Bean
CurrentTraceContext log4jTraceContext() {
return MDCCurrentTraceContext.create();
}

- 10,624
- 1
- 16
- 32
-
1
-
I just tried with log4j2. It should work out of the box as soon as you disable slf4j i.e set `spring.sleuth.log.slf4j.enabled=false` – Ashok Koyi Mar 29 '18 at 03:49
-
-
The correct dependency is `io.zipkin.brave:brave-context-log4j2` as explained [here](https://stackoverflow.com/a/57987624/). – stephan f Aug 12 '21 at 10:52
This is my example log4j2 configuration that logs in JSON including Sleuth's spanId
and traceId
.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
<Appenders>
<Console name="ConsoleJson" target="SYSTEM_OUT" follow="true">
<JsonLayout complete="false" compact="true" eventEol="true" properties="true"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="ConsoleJson"/>
</Root>
</Loggers>
</Configuration>
According to the log4j2 Layouts documentation:
properties
boolean
If true, the appender includes the thread context map in the generated JSON. Defaults to false.
So the thread context map is an actual holder of this information, to use it in other layouts (PatternLayout
) you must use some context map access keys like %X{spanId}
.