Spring Cloud Sleuth + log4j2

2020-08-24 03:28发布

问题:

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

回答1:

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();
}


回答2:

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}.