access to a pipeline job’s own Jenkins console log

elhay efrat
1 min readSep 15, 2019

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.

--

--