Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 473
Magnus Avatar asked Oct 12 '11 15:10

Magnus


People also ask

How do I print output in Groovy?

You can use the print function to print a string to the screen. You can include \n to embed a newline character. There is no need for semi-colon ; at the end of the statement. Alternatively you can use the println function that will automatically append a newline to the end of the output.

How do I integrate Groovy script in Jenkins?

To create Groovy-based project, add new free-style project and select "Execute Groovy script" in the Build section, select previously configured Groovy installation and then type your command, or specify your script file name. In the second case path taken is relatively from the project workspace directory.

Does Jenkins uses Groovy as its scripting language?

Jenkins features a Groovy script console which allows one to run arbitrary Groovy scripts within the Jenkins controller runtime or in the runtime on agents.


1 Answers

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)
like image 167
Magnus Avatar answered Oct 20 '22 20:10

Magnus