user2567728
user2567728

Reputation: 31

Adding logger to Jenkins pipeline shared library class

Trying to add logger to myClass. I want to see it in Jenkins console without using of "script.echo".

class myClass implements Serializable {
    def _logger
    def script
    myClass(def script, Map config) {
        _logger = script.getContext(TaskListener.class).getLogger()
        this.script = script
        this.config = config // some data
        log 'Initializing myClass...'
    }

    @NonCPS
    private void log(message) {
        _logger.println(message)
    }
...

def someMethod(){
    ...
    script.sh(someScript)
    ...
}
}

With this code in Jenkins console I see:

Initializing myClass...                <<<<<<<<<<<<<<<<<
[Pipeline] sh
[test-job] Running shell script
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
an exception which occurred:
    in field com.macys.devops.utils.myClass._logger
    in object com.macys.devops.utils.myClass@54e9341c
    in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals
    ....
    in field com.cloudbees.groovy.cps.Continuable.e
    in object org.jenkinsci.plugins.workflow.cps.SandboxContinuable@4c564ac6
    in field org.jenkinsci.plugins.workflow.cps.CpsThread.program
    ...
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@6b58d460
Caused: java.io.NotSerializableException: java.io.PrintStream

When I comment

this.script = script:

logger works, but I can't execute DSL commands (e.g. script.sh).

What I'm doing wrong?

Upvotes: 3

Views: 1984

Answers (1)

tkap
tkap

Reputation: 91

Try to move logger creation:

   _logger = script.getContext(TaskListener.class).getLogger()

to log method:

@NonCPS private void log(message) { script.getContext(TaskListener.class).getLogger().println(message) }

Upvotes: 4

Related Questions