Created
January 5, 2022 08:25
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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