【问题标题】:How to get MDC logging working for Spring Batch如何让 MDC 日志记录为 Spring Batch 工作
【发布时间】:2016-01-14 23:04:39
【问题描述】:

在 Spring Batch 中,通过日志记录跟踪执行线程会很棒。但是,MDC 似乎不起作用。

MDC.put("process", "batchJob"); logger.info("{}; status={}", getJobName(), batchStatus.name());

有人让 MDC 在 Spring Batch 中工作吗?

【问题讨论】:

  • 我想您必须重新定义 SB 包的日志配置文件,将额外信息(MDC 密钥、线程名称和其他信息)添加到 pattern 属性
  • 当然,已经完成了。

标签: spring-batch mdc


【解决方案1】:

我通过像这样添加JobExecutionListener 解决了这个问题:

public class Slf4jBatchJobListener implements JobExecutionListener {

    private static final String DEFAULT_MDC_UUID_TOKEN_KEY = "Slf4jMDCFilter.UUID";
    private final Logger logger = LoggerFactory.getLogger(getClass());

    public void beforeJob(JobExecution jobExecution) {
        String token = UUID.randomUUID().toString().toUpperCase();
        MDC.put(DEFAULT_MDC_UUID_TOKEN_KEY, token);
        logger.info("Job {} with id {} starting...", jobExecution.getJobInstance().getJobName(), jobExecution.getId());
    }

    public void afterJob(JobExecution jobExecution) {
        logger.info("Job {} with id {} ended.", jobExecution.getJobInstance().getJobName(), jobExecution.getId());
        MDC.remove(DEFAULT_MDC_UUID_TOKEN_KEY);
    }
}

因为某些作业是多线程的,所以我还必须添加一个 TaskDecorator 以便将 DMC 从父线程复制到子线程,如下所示:

public class Slf4JTaskDecorator implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable runnable) {
        Map<String, String> contextMap = MDC.getCopyOfContextMap();
        return () -> {
            try {
                MDC.setContextMap(contextMap);
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}

将TaskDecorator设置为TaskExecutor:

@Bean
public TaskExecutor taskExecutor(){
    SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor("spring_batch");
    taskExecutor.setConcurrencyLimit(maxThreads);
    taskExecutor.setTaskDecorator(new Slf4JTaskDecorator());
    return taskExecutor;
}

最后,更新属性中的日志记录模式:

logging:
  pattern:
    level: "%5p %X{Slf4jMDCFilter.UUID}"

【讨论】:

    猜你喜欢
    • 2019-01-31
    • 2011-02-20
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2014-02-07
    • 2015-05-01
    相关资源
    最近更新 更多