title: Append correlation id to every log java
body: <p>I need to append correlation id to logs from every request I get.</p>
  <p>Here is my filter. It works good until I get to async block like <code>runAsync()</code>.</p>
  <p><a href="https://i.stack.imgur.com/L4LQe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L4LQe.png" alt="logs" /></a></p>
  <p>I read about MDC and how it use ThreadLocal but can't understand how to use it in async because it uses ForkJoinPool.</p>
  <pre><code>@Component
  public class Slf4jFilter extends OncePerRequestFilter {
  
  private static final String CORRELATION_ID_HEADER_NAME = &quot;correlation-id&quot;;
  private static final String CORRELATION_ID_LOG_VAR_NAME = &quot;correlationId&quot;;
  
  @Override
  protected void doFilterInternal(HttpServletRequest request,
      HttpServletResponse response, FilterChain chain)
  throws ServletException, IOException {
      try {
          ofNullable(request.getHeader(CORRELATION_ID_HEADER_NAME)).ifPresent(correlationId -&gt; MDC
              .put(CORRELATION_ID_LOG_VAR_NAME, correlationId));
          chain.doFilter(request, response);
      }finally {
          removeCorrelationId();
      }
  }
  
  protected void removeCorrelationId() {
      MDC.remove(CORRELATION_ID_LOG_VAR_NAME);
  }
  }
  </code></pre>
  <p>logback.xml</p>
  <pre><code>&lt;configuration&gt;
  &lt;appender name=&quot;stdout&quot; class=&quot;ch.qos.logback.core.ConsoleAppender&quot;&gt;
      &lt;encoder class=&quot;ch.qos.logback.classic.encoder.PatternLayoutEncoder&quot;&gt;
          &lt;pattern&gt;%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread %X{correlationId}] %-5level %logger{36} - %msg %n&lt;/pattern&gt;
      &lt;/encoder&gt;
  &lt;/appender&gt;
  &lt;root level=&quot;INFO&quot;&gt;
      &lt;appender-ref ref=&quot;stdout&quot; /&gt;
  &lt;/root&gt;
  </code></pre>