简体   繁体   English

log4j2 线程上下文的配置

[英]Configuration of log4j2 Thread Context

In my spring boot application I'm using log4j2.在我的 Spring Boot 应用程序中,我使用的是 log4j2。 It's a typical web application.这是一个典型的 Web 应用程序。 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 .我正在两个终端中进行测试: 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. Log4j2 FAQ 有一个示例,说明如何使用RoutingAppender根据 ThreadContext 键将日志路由到不同的文件。

This uses the ThreadContext map, not the stack (so you'd need to use the put method instead of push ).这使用 ThreadContext 映射,而不是堆栈(因此您需要使用put方法而不是push )。

A bit late, but it is better if you use the MDC implementation for this with ThreadContext.put(key, value) .有点晚了,但如果您将 MDC 实现与ThreadContext.put(key, value)一起使用会更好。 It is important to use the correct configuration like {%20X}.使用正确的配置(如{%20X}.很重要{%20X}.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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