You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测Jenkins pipeline控制台错误并生成团队报告?

解决方案

1. 利用Jenkins Pipeline内置对象直接捕获日志

在Post阶段用Groovy代码调用currentBuild对象API获取完整构建日志,无需依赖外部脚本。示例:

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'echo "正常执行"; sleep 2; echo "模拟错误" >&2'
            }
        }
    }
    post {
        always {
            script {
                // 获取最后1000行日志(可按需调整行数)
                def buildLog = currentBuild.rawBuild.getLog(1000).join('\n')
                // 过滤错误信息,匹配Java异常、FAILED、ERROR等关键字
                def errors = buildLog =~ /(Exception|FAILED|ERROR)/
                if (errors.find()) {
                    // 生成报告内容
                    def report = "构建错误报告:\n构建编号: ${currentBuild.number}\n错误内容:\n${errors.getMatch(0).join('\n')}"
                    // 发送报告,示例使用邮件插件
                    emailext(
                        to: 'team@example.com',
                        subject: "构建失败 #${currentBuild.number}",
                        body: report
                    )
                }
            }
        }
    }
}

注意:若遇到权限问题,需在Jenkins全局安全配置中允许脚本访问rawBuild对象,调整Script Security Plugin的权限设置即可。

2. 提前捕获Stage级错误并收集信息

在每个Stage中用catchError或try-catch块捕获异常,将错误信息存入全局变量,最后在Post阶段汇总生成报告:

def errorList = []

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                    sh './build.sh'
                }
            }
            post {
                failure {
                    script {
                        def stageLog = currentBuild.rawBuild.getLog(500).reverse().findAll { it.contains('ERROR') }.reverse().join('\n')
                        errorList.add("Stage Build 失败:\n${stageLog}")
                    }
                }
            }
        }
        stage('Test') {
            steps {
                catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                    sh './test.sh'
                }
            }
            post {
                failure {
                    script {
                        def stageLog = currentBuild.rawBuild.getLog(500).reverse().findAll { it.contains('Exception') }.reverse().join('\n')
                        errorList.add("Stage Test 失败:\n${stageLog}")
                    }
                }
            }
        }
    }
    post {
        always {
            if (!errorList.isEmpty()) {
                def report = "构建错误汇总:\n\n${errorList.join('\n\n')}"
                emailext(
                    to: 'team@example.com',
                    subject: "构建 #${currentBuild.number} 存在错误",
                    body: report
                )
            }
        }
    }
}

这种方式能精准定位每个Stage的错误,避免全局日志筛选的繁琐。

3. 使用Email Extension插件的内置日志过滤

Email Extension插件支持直接在邮件配置中过滤日志内容,无需编写复杂脚本。Post阶段配置示例:

post {
    failure {
        emailext(
            to: 'team@example.com',
            subject: "构建失败 #${currentBuild.number}",
            body: """
                构建编号: ${currentBuild.number}
                错误日志片段:
                \${BUILD_LOG_REGEX, regex="(Exception|ERROR|FAILED)", linesBefore=2, linesAfter=10}
            """,
            attachLog: true // 可选:附上完整日志文件
        )
    }
}

该插件会自动匹配日志中的错误关键字,并提取前后上下文,适合快速生成错误报告。

4. 解决Shell脚本无法读取日志的问题

若坚持使用Shell脚本,可通过Jenkins构建日志API获取完整内容,而非直接读取控制台文件。Post阶段的Shell步骤示例:

# 通过API获取构建日志
BUILD_LOG=$(curl -s -u ${JENKINS_USER}:${JENKINS_TOKEN} "${JENKINS_URL}/job/${JOB_NAME}/${BUILD_NUMBER}/consoleText")
# 过滤错误信息
ERRORS=$(echo "$BUILD_LOG" | grep -E 'Exception|FAILED|ERROR')
# 生成报告并发送(示例用sendmail)
echo "构建错误报告:\n${ERRORS}" | sendmail team@example.com

需提前在Jenkins中配置用户Token,并确保脚本具备API访问权限。

内容的提问来源于stack exchange,提问作者Emmanuel Abdelnour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 15:47:10