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

Magnus picture Magnus · Oct 12, 2011 · Viewed 28.3k times · Source

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

Magnus picture Magnus · Oct 13, 2011

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 full solution.

import hudson.model.*

// Get the out variable
def out = getBinding().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)