Jenkins Shared Library instantiate util class and use in workflowscript

Viewed 9070

I'm creating my own Jenkins shared library to reuse some code between pipelines. I know how to create steps (really easy indeed) but I have a problem when I want to make accessible my "utils class" in the jenkinsfile (or WorkflowScript as Jenkins say in logs). I call "Util class" a groovy class located in folder src/my/domain/... that have many methods, for example, i want to create a log class like this:

# src/my/domain/group

package my.domain.group

class Console implements Serializable {

    def log(msg) {
        spit(msg, '\033[34m')
    }

    def error(msg) {
        spit(msg, '\033[31m')
    }

    def warning(msg){
        spit(msg, '\033[33m')
    }

    def success(msg){
        spit(msg, '\033[32m')
    }

    private def spit(msg, color){
        ansiColor('xterm') {
            echo color + msg + '\033[0m'
        }
    }

}

And then I try to instantiate in a file in /vars/library.groovy so can be accessed from the Jenkinsfile with some code as for example:

node("mynode"){
   console.log("Hello World!")
} 

The idea is to avoid to instantiate the console in all the script and make it automatically, I have tried several things like

# vars/library.groovy

import my.domain.group.Console
import groovy.transform.Field

@Field String console = new Console() 

or

# vars/library.groovy

import my.domain.group.Console

def load(){
    this.console = new Console() 
    // And also
    console = new Console()
}

But when trying to access from jenkins file I always get the error: groovy.lang.MissingPropertyException: No such property: console for class: WorkflowScript

I understand that this means that the instance is not at the right scope so cannot be directly seen by the script but how can I do that?

Thanks!

1 Answers
Related