Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spring TaskDecorator that propagates an SLF4J MDC to the runner's thread. Accounts for the possibility that the runner's thread is actually the same as the caller's thread by restoring the old MDC context, if existing.
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;
import java.util.Map;
public class MDCPropagatingTaskDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
Map<String, String> callerContext = MDC.getCopyOfContextMap();
if (callerContext == null) return runnable;
return () -> {
Map<String, String> executorContext = MDC.getCopyOfContextMap();
try {
MDC.setContextMap(callerContext);
runnable.run();
} finally {
MDC.clear();
if (executorContext != null) {
// intended for the case that we're running in the caller's thread
MDC.setContextMap(executorContext);
}
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment