Josh
Josh

Reputation: 371

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.

Upvotes: 1

Views: 3170

Answers (2)

Florian H.
Florian H.

Reputation: 359

You can fill the MDC in a listener, for example one that you add for each step. During the step's building (with its builder), do listener(logCompletingStepExecutionListener); with a (static-defined) listener like:

public class LogCompletingStepExecutionListener implements StepExecutionListener {

    private static final String LOG_MDC_CONTEXT_KEY_STEP_ID = "Step-ID";

    @Override
    public void beforeStep(StepExecution stepExecution) {
        StepExecutionListener.super.beforeStep(stepExecution);
        MDC.put(LOG_MDC_CONTEXT_KEY_STEP_ID, stepExecution.getStepName() + "_" + stepExecution.getJobExecutionId() + "_" + stepExecution.getId());
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        MDC.remove(LOG_MDC_CONTEXT_KEY_STEP_ID);
        return StepExecutionListener.super.afterStep(stepExecution);
    }
}

As said by @so-random-dude , it will not comes in other threads. For multi-threaded jobs, see the TaskDecorator in https://stackoverflow.com/a/68347374/7251133 (I didn't test it).

Upvotes: 0

so-random-dude
so-random-dude

Reputation: 16505

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.

Upvotes: 3

Related Questions