springspring-bootspring-batchlogbackmdc

Spring Batch MDC Logging


I'm wanting to know how to log things such as the Job Name and Execution ID using MCD in Spring Batch.

Here's some code:

bootstrap.properties

this file has a list of items I currently log, and I've added execId as the 3rd element here.

logging.pattern.level=%5p [%X{X-B3-TraceId:-},%X{sessionId:-},%X{execId:-},%X{program:-},%X{mainframeId:-}]
spring.application.name=mcc
spring.profiles.active=globals,local,local-override

MCC Application

this file has my main method. When I manually set the field here with MDC.put("execId", "12345"); I see it in the log, but I don't understand how to put the actual information I need here.

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class})
public class MccApplication {

    public static void main(String[] args) {
        MDC.put("execId", "12345");
        SpringApplication.run(MccApplication.class, args);
    }

}

I would appreciate any insight :) Thank you.


Solution

  • Disclaimer : I am not familiar with spring-batch

    MDC will work for you to log Job Name and Execution ID along with the log statements because MDC has a thread affinity. So if you put something to MDC while in a thread, then that will be available to you (and to logback) through out the lifecycle of that thread. So if you put MDC.put("execId", "12345"); in your main method, that will only be available in the main thread.

    The Job Name and Execution ID makes sense only in any child thread that the spring batch may spawn (I am running on wild assumptions here, as I am not familiar with spring batch). So add MDC.put("execId", "12345"); at the beginning point of your actual Job, not in the main() method.