Skip to content

Instantly share code, notes, and snippets.

@t3knoid
Created February 12, 2018 18:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save t3knoid/77a8903d79ff65194d06a610ec4a6b4b to your computer and use it in GitHub Desktop.
Save t3knoid/77a8903d79ff65194d06a610ec4a6b4b to your computer and use it in GitHub Desktop.
Progressively read a Jenkins job console output using Groovy
def jenkinsBase = // Set to Jenkins base URL
def jenkinsJob = // Set to Jenkins job name
def address = null
def response = null
def start = 0 // Start at offset 0
def cont = true // This semaphore holds the value of X-More-Data header value
try {
while (cont == true) { // Loop while X-More-Data value is equal to true
address = "${jenkinsBase}/job/${jenkinsJob}/lastBuild/logText/progressiveText?start=${start}"
println("${address}")
def urlInfo = address.toURL()
response = urlInfo.openConnection()
if (response.getResponseCode() != 200) {
throw new Exception("Unable to connect to " + address) // Throw an exception to get out of loop if response is anything but 200
}
if (start != response.getHeaderField('X-Text-Size')) { // Print content if the starting offset is not equal the value of X-Text-Size header
response.getInputStream().getText().eachLine { line ->
println(line)
}
}
start = response.getHeaderField('X-Text-Size') // Set new start offset to next byte
cont = response.getHeaderField('X-More-Data') // Set semaphore to value of X-More-Data field. If this is anything but true, we will fall out of while loop
sleep(3000) // wait for 3 seconds
}
}
catch (Exception ex) {
println (ex.getMessage())
}
@refactorsaurusrex
Copy link

This is awesome, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment