How to read console output in Jenkins during Build – 100% working code block

When you run a job in Jenkins, it generates a console output at run time which can be seen during a build. There are some cases when you run a build on Jenkins and you need to read the console output in Jenkins in a log file during the build. This may be due to any reason such as you want to extract a 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.

This method is written assuming that 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 created during a Jenkins job build, 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 in Jenkins
// 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 in Jenkins, All you need to do is 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.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.