javaspringspring-bootspring-cloud-sleuth

How to integrate Sleuth in a spring boot 1.5 to propagate trace id in newer spring boot 2.2?


We have a microservice architecture built with Spring Boot 2.2 and we are using Spring Cloud Sleuth to propagate the trace id.

However, we have one old huge monolithic built with Spring Boot 1.5.2 that it is not using Sleuth (upgrading this monolithic to Spring Boot 2.x is not an option). I have tried integrating Spring Cloud Sleuth 1.3.5 into this but it is not generating the Trace ID either (and found no documentation about it).

I currently coded this filter to log my transaction as an alternative, but I don't want to reinvent the wheel:

@Component
public class TransactionLoggingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String txnId = ofNullable(request.getHeader(TXN_ID_HEADER))
                .orElse(randomUUID().toString().substring(0, 8));

        MDC.put(TXN_ID, txnId);
        chain.doFilter(request, servletResponse);
        MDC.remove(TXN_ID);
    }
}

I was wondering how I can add Sleuth and programmatically create the trace/span id, so it can propagate seamlessly to other microservices using Spring Boot 2.2.

The older documentation I found about Spring Cloud Sleuth is 2.1.6. So, I found no way to use Sleuth with Spring Boot 1.5. Do you know if it is compatible with it and how I can integrate it?

I don't like above snippet because I'm creating another trace id that is not caught by Sleuth.


Solution

  • Have found the answer to my problem. Sharing for others that might find it useful.

    In order to use spring boot 1.5, the version of Spring Cloud Sleuth must be 1.3.6. The problem we had was that we have a custom logback.xml, and this was restricting Sleuth of printing the trace/span id.

    Therefore, when we added spring boot default.xml configuration in logback.xml, it started printing the needed logs:

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <!-- Needed for Sleuth to print the logs -->
        <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    
        <variable name="LOGS_DIR_VAR" value="${LOGS_DIR:-/logs}"/>
    
        <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>
                    %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}
                </pattern>
            </encoder>
        </appender>
    
        <root level="info">
            <appender-ref ref="STDOUT"/>
        </root>
    </configuration>