简体   繁体   中英

Configuration of log4j2 Thread Context

In my spring boot application I'm using log4j2. It's a typical web application. I have many connection and I want to separate logs for each connection.

I want to useThread Context :

@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test() throws InterruptedException
{
    try (final CloseableThreadContext.Instance ctc = CloseableThreadContext.push(UUID.randomUUID().toString()))
    {

        logger.info("start");
        Thread.sleep(1000);
        logger.info("end.");
    }
    return "response";
}

I'm testing in two terminals: curl localhost:8000/test . But I have the result:

14:09:27.895 [qtp401792389-21] INFO  Controllers.ContentController - start
14:09:28.062 [qtp401792389-19] INFO  Controllers.ContentController - start
14:09:28.896 [qtp401792389-21] INFO  Controllers.ContentController - end.
14:09:29.062 [qtp401792389-19] INFO  Controllers.ContentController - end.

It's mix of sessions, i want this:

14:09:27.895 [qtp401792389-21] INFO  Controllers.ContentController - start
14:09:28.896 [qtp401792389-21] INFO  Controllers.ContentController - end.
14:09:28.062 [qtp401792389-19] INFO  Controllers.ContentController - start
14:09:29.062 [qtp401792389-19] INFO  Controllers.ContentController - end.

So, is there any special configuration for this?

The Log4j2 FAQ has an example of how you can use the RoutingAppender to route logs to different files based on the ThreadContext key.

This uses the ThreadContext map, not the stack (so you'd need to use the put method instead of push ).

A bit late, but it is better if you use the MDC implementation for this with ThreadContext.put(key, value) . It is important to use the correct configuration like {%20X}.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM