How to read console output in Jenkins during Build

When you run a job in Jenkins, it generates a console output at run time. You can see it during a build. There are some cases when you run a build on Jenkins and you need to read the console output. You can read this console output and store it in a log file during the build. Later you can also extract this file from a virtual machine or dockerized container after the build completion. 

For sake of convenience, we have used groovy for our Jenkins pipeline script.

I am assuming you are aware of the concept of a stage in the Jenkins pipeline. If not, please refer to How to create a Jenkins pipeline.

In order to read the console output, we can create a stage to keep the script separate from the actual Jenkins job. 

The below script uses two functions writeFile and readFilewhich are provided in Jenkins by default.

Pipeline script in groovy example to read console output
// This stage is ready to use code block for capturing the console output to a txt file.
// Change the ProjectName and buildConsolelog file name as per your requirement

def directory = "${env.WORKSPACE}/ProjectName" // change name here
stage('capture console output') {

  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: directory + "/buildConsolelog.txt",
      text: logContent

  }
  def consoleOutput = readFile directory + '/buildConsolelog.txt'
  echo 'Console output saved in the buildConsolelog file'
  echo '--------------------------------------'
  echo consoleOutput
  echo '--------------------------------------'

}
How to use the pipeline script

This is a reusable code block for Jenkins read console output during a build.

In order to read the console output, just copy and paste the code as a stage in your pipeline script. After the build is run, a file named buildConsolelog.txt will be stored in the home directory of your project.

Related Posts