spring-projects / spring-batch

Spring Batch is a framework for writing batch applications using Java and Spring
http://projects.spring.io/spring-batch/
Apache License 2.0
2.71k stars 2.34k forks source link

Spring batch metrics is not aware of JobExecutionListener that modify job status #3963

Open qwazer opened 3 years ago

qwazer commented 3 years ago

I have a Spring Boot 2.5.2 app with spring-batch-4.3.3 The app has a multi-step job and a custom JobStatusReportingListener

@Component
public class JobStatusReportingListener implements JobExecutionListener {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void beforeJob(JobExecution jobExecution) {
    }

    @Override
    public void afterJob(JobExecution jobExecution) {

        List<StepExecution> failedSteps = jobExecution
                .getStepExecutions()
                .stream().filter(v -> !v.getExitStatus().equals(COMPLETED))
                .collect(Collectors.toList());

        if (!failedSteps.isEmpty()) {
            jobExecution.setStatus(BatchStatus.FAILED);
            jobExecution.setExitStatus(ExitStatus.FAILED);
            logger.error("Job failed on steps {}", failedSteps);
        }
    }
}

The problem is that metrics at actuator/metrics/spring.batch.job doesn't contain tags with status="FAILED" that is set by JobExecutionListener

fmbenhassine commented 1 year ago

Thank you for opening this issue. By looking at this snippet, I think this is a valid issue. In fact, the observation is stopped and the status is recorded before listeners are called. Therefore, any status change done in the listener is not reflected in the final metric.

That said, I would like to validate that with a failing test or a minimal complete example that reproduces the issue. This failing test or minimal example will be used to validate the bug as well as the fix. Please take some time to create a minimal example that reproduces the problem. To help you in reporting your issue, we have prepared a project template that you can use as a starting point. Please check the Issue Reporting Guidelines for more details about this.

Thank you for your collaboration.