Jenkins DSL, Get "stage logs" as list and print the failures

Hi,
I am working with Jenkis [DSL].
Do you know a Jenkins API to get all the logs of the JOB?

For example, there is a method to get console output:

def x = currentBuild.getRawBuild().getLog()

If there is an API, is it possible to convert the stage logs to a list and print the error log where the stage failed (red color)?

I am trying to print the relevant error and not all console outputs like

def x = currentBuild.getRawBuild().getLog()
println (x)

Desired process:

Thanks,
Oded

Hello @oded and welcome to this community :wave:

I may be wrong, but I think you can use the getLogText() method to retrieve the entire console log as a string.

To extract the logs for a particular stage, you could maybe use the Jenkins Pipeline step([$class: 'LogParserStep']) step. This step is used to parse and extract data from log files generated during a build.

Here is an example of how you could extract the error logs from the console output of a specific stage:

def logParser = [:]
stage('Build') {
    try {
        // Build stage logic here
    } catch (e) {
        logParser = step([$class: 'LogParserStep', 
            parsingRulesPath: 'path/to/parsing/rules'])
        // parsingRulesPath is optional if you have defined rules inline
        // use the parsed data to extract the relevant error logs
        def errorLogs = logParser["errors"]
        println(errorLogs)
        throw e
    }
}

In the above example, the LogParserStep step is used to extract data from the console log generated during the build stage. The parsed data is then used to extract the error logs and print them to the console.

You can define your own parsing rules to extract the relevant error logs. The parsingRulesPath parameter can be used to specify the path to the parsing rules file. If the parsing rules are defined inline, you can omit the parsingRulesPath parameter.

Some update for you. I had similar situation, but I had to get logs for specific stage. It was challenging task for me, so I want to share solution with community. The code below obtains logs of specific stage by name:

import java.util.regex.Matcher
import java.util.regex.Pattern

import org.jenkinsci.plugins.workflow.actions.LabelAction
import org.jenkinsci.plugins.workflow.actions.LogAction
import org.jenkinsci.plugins.workflow.graph.FlowNode
import org.jenkinsci.plugins.workflow.graphanalysis.DepthFirstScanner
import org.jenkinsci.plugins.workflow.cps.nodes.StepStartNode
import org.jenkinsci.plugins.workflow.job.WorkflowRun
import java.util.stream.Collectors

    // Recursively check flowNode parents until we find a stage
    @NonCPS
    static String getFlowNodeStage(FlowNode flowNode) {
        for (FlowNode parent : flowNode.getParents()) {
            if (parent instanceof StepStartNode && isNamedStageStartNode(parent)) {
                return parent.getAction(LabelAction.class).getDisplayName()
            } else {
                return getFlowNodeStage(parent)
            }
        }
        // Return null if no stage found. Null will be passed through all recursion levels
        return null
    }

    // Collect logs of each flow node that belongs to stage
    @NonCPS
    static List<String> collectLogsForStage(WorkflowRun run, String stageName) {
        run.save()
        List<String> logs = []
        DepthFirstScanner scanner = new DepthFirstScanner()

        scanner.setup(run.getExecution().getCurrentHeads())

        for (FlowNode flowNode : scanner) {
            // Skip flow nodes that are not part of a requested stage
            // If stage not found for the current flow node, getFlowNodeStage() will return null
            if(stageName.equals(getFlowNodeStage(flowNode))) {
                LogAction logAction = flowNode.getAction(LogAction.class)
                if (logAction != null) {
                    def reader = new BufferedReader(logAction.getLogText().readAll())
                    List<String> flowNodeLogs = reader.lines().collect(Collectors.toList())
                    logs.addAll(0, flowNodeLogs)
                }
            }
        }
        return logs
    }

    @NonCPS
    static private boolean isNamedStageStartNode(FlowNode node) {
        return Objects.equals(((StepStartNode) node).getStepName(), "Stage") && !Objects.equals(node.getDisplayFunctionName(), "stage");
    }

To obtain logs for specific stage you just need to call collectLogsForStage() function with currentBuild.rawBuild as WorkflowRun and stage name
Example:

List<String> stageLogs = collectLogsForStage(currentBuild.rawBuild, "Test")