将记录器添加到Jenkins管道共享库类

时间:2018-09-20 18:51:04

标签: class logging groovy jenkins-pipeline shared

尝试将记录器添加到myClass。我想在Jenkins控制台中看到它而不使用“ 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)
    ...
}
}

在Jenkins控制台中使用此代码,我看到:

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

当我发表评论

  

this.script =脚本:

记录器可以工作,但是我无法执行DSL命令(例如script.sh)。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试移动记录器的创建:

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

记录方法:

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