Get a job’s console logfile from a Jenkins pipeline

Here’s a short tip describing how to access to a pipeline job’s own Jenkins console log. You may need it for whatever purpose, whether it is archiving the logs along with the created artifact or taking any build decision after analyzing the logs.


stage('save log build') {
    steps {
        script {
            def logContent = Jenkins.getInstance()
                .getItemByFullName(env.JOB_NAME)
                .getBuildByNumber(
                    Integer.parseInt(env.BUILD_NUMBER))
                .logFile.text
            // copy the log in the job's own workspace
            writeFile file: "buildlog.txt", text: logContent
        }
    }
}

Simple isn’t it ? Well… Wait a minute, there are caveats:

  1. it seems like this must be done on a specific “stage” of it’s own, otherwise Jenkins may not have flushed all the logs to the file.
  2. This uses “risky” groovy so once you wrote it, you have to go a few times to the “in-script process approval” config screen to approve some method signature. Yes, this is unsafe as it opens the door to attacks on your Jenkins instance. But when it’s not Internet facing, the risk may be worth it. You decide.

The good part is that it (seem to) works (at least for now) whether run from the Jenkins master or a slave.

That’s it for today !

7 thoughts on “Get a job’s console logfile from a Jenkins pipeline

  1. The File is not at all readable.It has all encoding stuff. Do u have suggestion to get a readable console out put as a text file?

  2. how can you just access only the log of a particular stage within the pipeline using the above syntax? for example one of my stages is called ‘Test’ and I want just that log to be written into the txt file.

    1. I don’t know any easy solution. One very dirty workaroud would be to get the log text BEFORE your ‘test’ stage and then also AFTER and to deduce that only new lines were created by the ‘test’ stage. I think this would work despite not being very elegant !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s