package cn.reghao.tnb.content.app.config;

import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.Map;

/**
 * 解决线程异步场景下 RequestId 的在 logback 中的打印问题
 *
 * @author reghao
 * @date 2025-07-18 09:18:16
 */
public class MdcTaskDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        // Capture the context of the current thread (the main thread)
        Map<String, String> contextMap = MDC.getCopyOfContextMap();
        return () -> {
            try {
                // Set the context map for the child thread
                if (contextMap != null) {
                    MDC.setContextMap(contextMap);
                }
                runnable.run();
            } finally {
                // Clear the context map after the child thread has finished
                MDC.clear();
            }
        };
    }
}
