Fail Gradle build when anything on standard error

847 Views Asked by At

How can I configure Gradle to fail build at the end (not fail fast) if there is anything printed on standard error output by any task or plugin?

I haven't found a way to do it in the official API.

1

There are 1 best solutions below

0
On BEST ANSWER

Here’s a sample build.gradle that shows how this can work:

// create a listener which collects stderr output:
def errMsgs = []
StandardOutputListener errListener = { errMsgs << it }

// add the listener to both the project *and* all tasks:
project.logging.addStandardErrorListener errListener
project.tasks.all { it.logging.addStandardErrorListener errListener }

// evaluate the collected stderr output at the end of the build:
gradle.buildFinished {
  if (errMsgs) {
    // (or fail in whatever other way makes sense for you)
    throw new RuntimeException(errMsgs.toString())
  }
}


// example showing that the project-level capturing of stderr logs works:
if (project.hasProperty('projErr'))
  System.err.print('proj stderr msg')

// example showing that the task-level capturing of stderr logs works:
task foo {
  doLast {
    System.err.print('task stderr msg')
  }
}

// example showing that stdout logs are not captured:
task bar {
  doLast {
    System.out.print('task stdout msg')
  }
}

The examples in the second half are only there to show that it works as expected. Try the build with various command line args/options:

# doesn’t fail:
./gradlew bar
# fails due to project error:
./gradlew -PprojErr bar
# fails due to task error:
./gradlew foo
# fails due to both task and project error:
./gradlew -PprojErr foo