Magnus Magnus - 2 months ago 25
Groovy Question

Groovy-script in jenkins println output disappears when called inside class environment

The output from println from within a class function is lost.

An example script (outputclass.groovy):

class OutputClass
{
OutputClass()
{
println("Inside class") // This will not show in the console
}
}

println("Outside class") // Only this is shown in the console
output = new OutputClass()


I use Jenkins CLI to execute the groovy script

java -jar ..\jenkins-cli.jar -s JENKINS_SERVER_URL groovy outputclass.groovy


It only outputs this:


Outside class


It seems like the class inmplicitly uses println from System.out.println, and System.out is directed to the log files, but the println outside the class is using something else, which is outputted in the script console. The following code shows the behavior.

System.out.println("First")
println("Second")


Output:


Second


How do I explicitly set the output device to output to the Jenkins script console?

Answer

I found the solution myself here http://mriet.wordpress.com.

When the Groovy plugin starts is passes two bindings to the script. From the bindings we can get the out variable. Get it and use out.println to output to the script console, not the plain println.

The script below shows the solution.

import hudson.model.*

// Get the out variable
def config = new HashMap()
def bindings = getBinding()
config.putAll(bindings.getVariables())

def out = config['out']

class OutputClass
{
    OutputClass(out)  // Have to pass the out variable to the class
    {
    out.println ("Inside class")
    }
}

out.println("Outside class")
output = new OutputClass(out)
Comments