访问MDC的职位信息 [英] Accessing Job information for MDC
问题描述
我正在尝试用MDC记录工作信息.我有一个名为CommonBatchConfiguration
的文件,用于处理线程和记录作业信息.我想记录诸如jobName
和executionId
之类的内容,以进行可能运行的任何作业.
I'm trying to log job info with MDC. I've got a file called CommonBatchConfiguration
that handles threading and logging job info. I want to log things like jobName
and executionId
for any job that may run.
我有一个这样的启动器:
I've got a launcher like this:
@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
时,它总是显示为空
how can I access the job info here? When I try using JobExecution
it always comes up null
推荐答案
调用修饰的可运行对象时,应该已经创建了作业执行.问题是如何在这一点上访问它?我不确定这是否容易,除非您能够自省
The job execution should be already created when your decorated runnable is invoked. The question is how to get access to it at this point? I'm not sure if this would be easy unless you are able to introspect a final variable in a method of an anonymous inner class instance (the runnable created by Spring Batch) wrapped in an anonymous inner class instance (your decorator) :-)
我想为任何可能运行的作业记录诸如jobName和executionId之类的信息.
I want to log things like jobName and executionId for any job that may run.
您可能不需要任务装饰器.您可以做的是子类SimpleJobLauncher
并覆盖run
,类似:
You probably don't need to have a task decorator. What you can do is subclass SimpleJobLauncher
and override run
, something like:
@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;
}
这篇关于访问MDC的职位信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!