herm
herm

Reputation: 16405

Jenkins pipeline capture output of jenkins steps

How can I archive (as a file) the console output of a jenkins pipeline step such as docker.build(someTag)?

Background:

I use jenkins pipelines to build a whole bunch of microservices.

I want to extract all the relevant information from the jenkins console into archived files, so that devs don't have to look at the console which confuses them. This works fine for sh steps were I can redirect stdout and stderr but how can I do something similar for a jenkins pipeline step?

Upvotes: 3

Views: 2887

Answers (2)

user1403938
user1403938

Reputation: 1

Here's what I'm using to capture the sha256 of the built docker image

docker.build(someTag)
def dockerSha256 = sh(returnStdout: true, script: "docker image inspect $someTag | jq .[0].Id").trim()

I'm using 'jq' to parse the json response

or the groovy way

    def json = sh(returnStdout: true, script: "docker image inspect $someTag").trim()
    def obj = new JsonSlurper().parseText(json)

    println "raw json: " + obj
    println "groovy docker sha256: " + obj[0].Id

Upvotes: -1

Joerg S
Joerg S

Reputation: 5149

As a workaround we use following LogRecorder class:

class LogRecorder implements Serializable {
    def logStart
    def logEnd
    def currentBuild
    def steps

    LogRecorder(currentBuild) {
        this.currentBuild = currentBuild
    }

    void start() {
        logStart = currentBuild.getRawBuild().getLog(2000)
    }

    String stop() {
        logEnd = currentBuild.getRawBuild().getLog(2000)
        getLog()
    }

    String getLog() {
        def logDiff = logEnd - logStart
        return logDiff.join('\n')
    }
}

Depending on your needs you may want to adjust the number of log lines in the calls to getLog().

Possible Usage:

LogRecorder logRecorder = new LogRecorder(currentBuild)
logRecorder.start()

docker.build(someTag)

testResult.stdOut = logRecorder.stop()

Please be aware that it may happen - most probably due to caching issues - that the very last line(s) of the log are sometimes missing. Maybe a sleep would help here. But so far this was not required here.

Upvotes: 2

Related Questions