2017-01-15 41 views
1

在我的spring引导应用程序中,我使用了log4j2。这是一个典型的Web应用程序。我有很多连接,我想为每个连接分开日志。配置log4j2线程上下文

我想用Thread 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"; 
} 

我在两个终端测试:curl localhost:8000/test。但我的结果:

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. 

这是会议的搭配,我想这一点:

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. 

那么,有没有什么特别的配置吗?

回答

0

Log4j2 FAQ has an example说明如何使用RoutingAppender根据ThreadContext键将日志路由到不同的文件。

这使用ThreadContext地图,而不是堆栈(所以你需要使用put方法,而不是push)。

0

有点迟了,但是如果您使用MDC实现与ThreadContext.put(key, value)更好。使用正确的配置很重要,如{%20X}.