calembredaine
calembredaine

Reputation: 93

Log the value of a Spring Cloud Sleuth Baggage in the current Span Context

I have a Spring Boot app (version 2.1.3.RELEASE) using Spring Cloud Sleuth and I would like to log the value of a baggage in the current Span Context. I am using Logback.

My logger has this logback configuration:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>
                %date{ISO8601} %highlight(%-5level) %magenta(%thread) %cyan(%logger) %message %X{X-B3-TraceId} %X{X-B3-SpanId} %X{foo}%n
            </pattern>
        </encoder>
    </appender>
    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

In my Controller, I am trying to set a baggage on the current Span Context:

Span currentSpan = this.tracer.currentSpan();
ExtraFieldPropagation.set(currentSpan.context(), "foo", "bar");

In my application.properties, I have set the following properties:

spring.sleuth.propagation-keys=foo
# Set the value of the foo baggage into MDC:
spring.sleuth.log.slf4j.whitelisted-mdc-keys=foo

But I am not able to log the value of foo (with %X{foo}). The result is an empty string for foo:

My message e575e59578b92ace e575e59578b92ace 

Upvotes: 0

Views: 1778

Answers (1)

Moronito
Moronito

Reputation: 11

The whitelisted baggage values set in the current span are written in SLF4J MDC in org.springframework.cloud.sleuth.log.Slf4jScopeDecorator.decorateScope(), so if a new child span is created you will find the baggage value in the logs.

I am currently unaware of an elegant way of getting MDC updated as soon as a baggage value is set.

The only solution I have come up with is to manually set the value in MDC. In your case that would mean something like

org.slf4j.MDC.put("foo", "bar");

Hope this helps

Upvotes: 1

Related Questions