Skip to content

Instantly share code, notes, and snippets.

@jkuipers
Created January 5, 2022 08:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkuipers/cee63cede70e631db77217f6836ad4b9 to your computer and use it in GitHub Desktop.
Save jkuipers/cee63cede70e631db77217f6836ad4b9 to your computer and use it in GitHub Desktop.
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