简体   繁体   English

Spring Boot MDC继承行为是否已更改?

[英]Has spring boot MDC inheritance behaviour changed?

Until recently I was using spring-boot 1.3.5.RELEASE and the following worked. 直到最近,我仍在使用spring-boot 1.3.5.RELEASE,以下代码可以正常工作。

@SpringBootApplication
public class MyApplication {
    static {
        MDC.put("service_name", "myapp");
    }
    public static void main(String[] args) {
        SpringApplication.run(new Object[]{MyConfiguration.class}, args);
    }
}

Note the MDC put. 请注意MDC放置。 The service_name was then logged in each log line in the entire application using the logback logger. 然后使用logback记录器将service_name记录在整个应用程序的每个日志行中。 This was true even in child threads eg MVC controllers. 即使在子线程(例如MVC控制器)中也是如此。

We are now on spring version 1.4.1.RELEASE and the MDC logging of service_name only works in the main thread now, and not MVC controller threads. 我们现在使用的是1.4.1.RELEASE的春季版本,service_name的MDC日志现在仅在主线程中起作用,而在MVC控制器线程中不起作用。

"myapp" is still logged in the main thread: “ myapp”仍记录在主线程中:

2016-11-30 14:22:08,147 [main] INFO  co.uk.me.MyApplication - myapp [,,] - Started MyApplication in 14.276 seconds (JVM running for 308.404)

But in a controller log line "myapp" is now missing. 但是现在在控制器日志行中缺少“ myapp”。

2016-11-30 15:17:50,329 [http-nio-9007-exec-2] INFO  co.uk.me.controller.MyController -  [,,] - Received get <snip>

Before the change it looked like: 在更改之前,它看起来像:

2016-11-30 15:17:50,329 [http-nio-9007-exec-2] INFO  co.uk.me.controller.MyController - myapp [,,] - Received get <snip>

I can see in the debugger that the MDC context is empty at the start of the controller method. 我在调试器中看到在控制器方法开始时MDC上下文为空。

Does anyone know what change has affected this behaviour? 有谁知道什么变化影响了这种行为? Maybe a change to spring MVC thread creation? 也许对Spring MVC线程创建进行了更改? Or a logback change? 还是注销更改? Is there a way to set and keep an application-wide MDC property still in spring-boot? 有没有一种方法可以设置和保持应用程序范围的MDC属性仍在spring-boot中?

Thanks 谢谢

The MDC values are kept on thread locals, so only the main thread that starts your spring boot app has the value. MDC值保留在线程局部变量上,因此只有启动Spring Boot应用程序的主线程才具有该值。 MDC usually used for dynamic content and not for static (application name is not going to change). MDC通常用于动态内容,而不用于静态内容(应用程序名称不会更改)。 You can add a filter that will populate the MDC value on every incoming request. 您可以添加一个过滤器,该过滤器将在每个传入请求中填充MDC值。

I recommend to use something like this in you logback-spring.xml file: 我建议在您的logback-spring.xml文件中使用以下内容:

        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%date [myapp] [%thread] %-5level %logger{36} - %msg%xEx%n</Pattern>
        </encoder> 

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

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