At first glance your code looks okay. You can verify by printing the context data as part of the logging output. (Either in your test program or in configuration by adding %X in the PatternLayout pattern.)
Remko (Shameless plug) Every java main() method deserves http://picocli.info > On Apr 15, 2018, at 15:09, Franz Wong <franzw...@gmail.com> wrote: > > Hi, > > How do I pass the thread context to another thread? > > I created a decorator for ExecutorService. It copies the context from > source thread and copy to the target thread. > > I am not sure whether this is the right approach or not. I saw something > called ContextDataInjector but I don't understand the usage of it. > > Decorator: > > public class ThreadContextAwareExecutorService extends > AbstractExecutorService { > > private ExecutorService executorService; > > public ThreadContextAwareExecutorService(ExecutorService > executorService) { > this.executorService = executorService; > } > > @Override > public void execute(Runnable command) { > if (command == null) > throw new NullPointerException(); > Map<String, String> context = ThreadContext.getContext(); > Runnable wrappedCommand = () -> { > ThreadContext.clearMap(); > ThreadContext.putAll(context); > command.run(); > }; > executorService.execute(wrappedCommand); > } > > // ignore other decorated methods > } > > Sample code: > > public class MainApplication { > private static final Logger logger = > LogManager.getLogger(MainApplication.class); > private static final ExecutorService executor = new > ThreadContextAwareExecutorService(ForkJoinPool.commonPool()); > > public static void main(String[] args) throws Exception { > ThreadContext.put("REQUEST-ID", UUID.randomUUID().toString()); > logger.info("message 1"); > CompletableFuture<String> future = CompletableFuture.supplyAsync(() > -> { > logger.info("message 2"); > return "hello"; > }, executor); > future.get(); > } > } --------------------------------------------------------------------- To unsubscribe, e-mail: log4j-user-unsubscr...@logging.apache.org For additional commands, e-mail: log4j-user-h...@logging.apache.org