logging-log4j-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Franz Wong <franzw...@gmail.com>
Subject Re: How do I pass the thread context to another thread?
Date Mon, 16 Apr 2018 03:23:05 GMT
Ok, I will try. Thanks for your reply :)

Franz

On Sun, Apr 15, 2018 at 3:54 PM, Remko Popma <remko.popma@gmail.com> wrote:

> 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 <franzwong@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-unsubscribe@logging.apache.org
> For additional commands, e-mail: log4j-user-help@logging.apache.org
>
>

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message