I need to append correlation id to logs from every request I get.
Here is my filter. It works good until I get to async block like runAsync()
.
I read about MDC and how it use ThreadLocal but can't understand how to use it in async because it uses ForkJoinPool.
@Component
public class Slf4jFilter extends OncePerRequestFilter {
private static final String CORRELATION_ID_HEADER_NAME = "correlation-id";
private static final String CORRELATION_ID_LOG_VAR_NAME = "correlationId";
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
try {
ofNullable(request.getHeader(CORRELATION_ID_HEADER_NAME)).ifPresent(correlationId -> MDC
.put(CORRELATION_ID_LOG_VAR_NAME, correlationId));
chain.doFilter(request, response);
}finally {
removeCorrelationId();
}
}
protected void removeCorrelationId() {
MDC.remove(CORRELATION_ID_LOG_VAR_NAME);
}
}
logback.xml
<configuration>
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread %X{correlationId}] %-5level %logger{36} - %msg %n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="stdout" />
</root>
Here's the solution I ended up. Thanks to @M.Prokhorov
Create a class called
MdcRetention
inside your project.Then wrap your Runnable inside
runAsync()
block using static methodMdcRetention.wrap()
Before:
runAsync(() -> someMethod());
After:
runAsync(wrap(() -> someMethod()));