title: How to avoid manual cleanup when using baggage with Spring Cloud Sleuth and MDC?
body: <p>I have several Spring Boot + Sleuth 2.1 based micro services (A, B and C) that make HTTP requests from one to another (A->B->C). I'm using Sleuth to pass additional parameter 'x-session-id' (baggage) between the applications as HTTP request header and use SLF4J to log the value of the parameter in log statements. For this I have configured in application.yml:</p>
  
  <pre><code>spring.sleuth:
    propagation-keys:
      - x-session-id
    log:
      slf4j:
        whitelisted-mdc-keys: x-session-id 
  </code></pre>
  
  <p>And in logback-spring.xml the pattern value is:</p>
  
  <pre><code>%d{HH:mm:ss.SSS} %-5level [xSessionId=%X{x-session-id:-},traceId=%X{X-B3-TraceId:-}] [%thread] %logger : %m%n
  </code></pre>
  
  <p>Everything works when I set the HTTP header "x-session-id" externally (so I make request to A with header x-session-id and the value is automatically passed from A to B and from B to C). So the value moves between applications and appears on log statements of each application.</p>
  
  <p>But when I generate the value of x-session-id inside the application (let's say inside A) and set the value to Sleuth programmatically (instead of passing it as HTTP request header) then the header is added to outgoing requests normally but SLF4J doesn't know about it and log statements don't show out the value. This is how I make Sleuth aware (I @Autowire tracer):</p>
  
  <pre><code>Span continuedSpan = tracer.toSpan(span.context());
  ExtraFieldPropagation.set(continuedSpan.context(), "x-session-id", "mySession123");
  </code></pre>
  
  <p>However when I explicitly pass the value to MDC like this:</p>
  
  <pre><code>org.slf4.MDC.put("x-session-id", "mySession123");
  </code></pre>
  
  <p>then it stays with the thread even after the request completes and I have to clean it up manually. For this I have created separate interceptor: </p>
  
  <pre><code>@Component
  public class CleanupBaggageInterceptor extends HandlerInterceptorAdapter {
      private static final Logger logger = LoggerFactory.getLogger(CleanupBaggageInterceptor.class);
  
      @Override
      public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) {
          logger.debug("Cleaning up any baggage that has manually been set to MDC");
          MDC.clear();
      }
  
  }
  </code></pre>
  
  <p>and registered the interceptor with the app:</p>
  
  <pre><code>@Configuration
  public class MidGatewayConfiguration implements WebMvcConfigurer {
  
      @Override
      public void addInterceptors(InterceptorRegistry registry) {
          registry.addInterceptor(new CleanupBaggageInterceptor());
      }
  }
  </code></pre>
  
  <p>Is there any way to set the baggage value to Sleuth in a way that Sleuth itself sets it to MDC (and cleans it up after the request the same way it cleans up traceId)?</p>