Magnus Magnus - 7 months ago 59
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
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.




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


I found the solution myself here

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()

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)