将关联 ID 附加到每个日志 java

Append correlation id to every log java

我需要将相关 ID 附加到我收到的每个请求的日志中。

这是我的过滤器。在我进入像 runAsync().

这样的异步块之前,它一直很好用

我了解了 MDC 以及它如何使用 ThreadLocal,但无法理解如何在异步中使用它,因为它使用 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>

这是我最终得到的解决方案。感谢@M.Prokhorov

在您的项目中创建一个名为 MdcRetention 的 class。

public final class MdcRetention {

public static Runnable wrap(final Runnable delegate) {
    return new MdcRetainingRunnable() {
        @Override
        protected void runInContext() {
            delegate.run();
        }
    };
}

private static abstract class MdcRetentionSupport {
    protected final Map<String, String> originalMdc;

    protected MdcRetentionSupport() {
        Map<String, String> originalMdc = MDC.getCopyOfContextMap();
        this.originalMdc = originalMdc == null ? Collections.emptyMap() : originalMdc;
    }
}

public static abstract class MdcRetainingRunnable extends MdcRetentionSupport implements Runnable {

    @Override
    public final void run() {
        Map<String, String> currentMdc = MDC.getCopyOfContextMap();
        MDC.setContextMap(originalMdc);
        try {
            runInContext();
        } finally {
            MDC.setContextMap(currentMdc);
        }
    }

    abstract protected void runInContext();
}}

然后使用静态方法 MdcRetention.wrap()

将 Runnable 包裹在 runAsync() 块中

之前: runAsync(() -> someMethod());

之后: runAsync(wrap(() -> someMethod()));