6

Consider a Jenkins Pipeline with two stages, Stage A then Stage B.

In Stage B, is it possible to parse the logs of Stage A for some particular text?

Chadi
  • 737
  • 1
  • 6
  • 21
  • I depends what kind of logs you need. E.g. if you want parse gradle output probably you can redirect standard output to file and next read file and parse it. – krynio Jul 06 '16 at 08:46

3 Answers3

6

Use tee to split the output to both stdout and file. Next parse the file for your text.

STAGE_A_LOG_FILE = 'stage_a.log'

pipeline {
    agent any
    stages {
        stage('Stage A') {
            steps {
                script {
                    // tee log into file
                    tee(STAGE_A_LOG_FILE) {
                        echo 'print some Stage_A log content ...'
                    }
                }
            }
        }
        stage('Stage B') {
            steps {
                script {
                    // search log file for 'Stage_A'
                    regex = java.util.regex.Pattern.compile('some (Stage_A) log')
                    matcher = regex.matcher(readFile(STAGE_A_LOG_FILE))
                    if (matcher.find()) {
                        echo "found: ${matcher.group(1)}"
                    }
                }
            }
        }
    }
}

Pipeline output:

print some Stage_A log content ...
found: Stage_A
Finished: SUCCESS
Gerasim
  • 61
  • 1
  • 4
5

There's been an update since July 28th !

As mentionned in this answer, as of version 2.4 of Pipeline: Nodes and Processes you can use:

def out = sh script: 'command', returnStdout: true

At least it's much more simple and clean than outputting to a file and reading the file afterwards.

Community
  • 1
  • 1
Pom12
  • 7,622
  • 5
  • 50
  • 69
  • 1
    Hi, maybe you can help me to parse a previous "step", because I used the **copyArtifact** plugin which needs a "step" (so in my case it's not a command, so I can't use "sh script"), I created a question for it: https://stackoverflow.com/questions/46601108/jenkins-copy-artifact-parse-copied-build-id – firepol Oct 06 '17 at 08:06
1

If you want to search for the first occurrance of a pattern, you can also use manager.logContains(regexp) or manager.getLogMatcher(regexp). See my other answer for more details: https://stackoverflow.com/a/39873765/4527766

Community
  • 1
  • 1
Sergej Werfel
  • 1,335
  • 2
  • 14
  • 25