0

Until recently I was using spring-boot 1.3.5.RELEASE and the following worked.

@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. The service_name was then logged in each log line in the entire application using the logback logger. This was true even in child threads e.g. MVC controllers.

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.

"myapp" is still logged in the main thread:

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.

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.

Does anyone know what change has affected this behaviour? Maybe a change to spring MVC thread creation? Or a logback change? Is there a way to set and keep an application-wide MDC property still in spring-boot?

Thanks

Rob H
  • 3
  • 4
  • Not related with Spring boot but with setting an application-wide MDC property: https://stackoverflow.com/a/51678672/3320400 – mgsCatDev Aug 03 '18 at 19:17

1 Answers1

0

The MDC values are kept on thread locals, so only the main thread that starts your spring boot app has the value. MDC usually used for dynamic content and not for static (application name is not going to change). You can add a filter that will populate the MDC value on every incoming request.

I recommend to use something like this in you logback-spring.xml file:

        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%date [myapp] [%thread] %-5level %logger{36} - %msg%xEx%n</Pattern>
        </encoder> 
Maxim Kirilov
  • 2,639
  • 24
  • 49