访问MDC的职位信息

时间:2018-09-04 17:46:20

标签: java spring logging spring-batch

我正在尝试用MDC记录工作信息。我有一个名为CommonBatchConfiguration的文件,用于处理线程和记录作业信息。我想记录jobNameexecutionId之类的内容,以记录可能运行的任何作业。

我有一个这样的启动器:

@Bean(name = "AsyncMccJobLauncher")
    public JobLauncher simpleJobLauncher(JobRepository jobRepository) {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        jobLauncher.setJobRepository(jobRepository);
        SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
        taskExecutor.setTaskDecorator(new TaskDecorator() {

            @Override
            public Runnable decorate(Runnable runnable) {
//                MDC.put("execId", jobExecution.getJobId());
//                MDC.put("jobName", "test jobName");

                return new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        // This adds batch logging info while the job is running
//                        MDC.put("execId", "here");
//                        MDC.put("jobName", "here");
                        runnable.run();
                    }
                };
            }
        });
        jobLauncher.setTaskExecutor(taskExecutor);
        return jobLauncher;
    }

如何在此处访问工作信息?当我尝试使用JobExecution时,它总是出现空值

1 个答案:

答案 0 :(得分:0)

在调用修饰的可运行对象时,应该已经创建了作业执行。问题是如何在这一点上访问它?我不确定这是否容易,除非您能够在包裹在匿名内部类实例(您的装饰器)中的匿名内部类实例(由Spring Batch创建的runnable)的方法中对final variable进行自省:-)

  

我想为任何可能运行的作业记录jobName和executionId之类的信息。

您可能不需要任务装饰器。您可以做的是子类SimpleJobLauncher并覆盖run,例如:

@Bean(name = "AsyncMccJobLauncher")
public JobLauncher simpleJobLauncher(JobRepository jobRepository) {
    SimpleJobLauncher jobLauncher = new SimpleJobLauncher() {
        @Override
        public JobExecution run(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
            JobExecution jobExecution = super.run(job, jobParameters);
            // jobExecution is created and accessible here
            //MDC.put("execId", String.valueOf(jobExecution.getJobId()));
            //MDC.put("jobName", jobExecution.getJobInstance().getJobName());
            return jobExecution;
        }
    };
    jobLauncher.setJobRepository(jobRepository);
    SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
    jobLauncher.setTaskExecutor(taskExecutor);
    return jobLauncher;
}