如何在Jenkins失败邮件中告知失败阶段及对应错误日志?
Great question! Adding the specific failed stage name and its error logs to your failure notification email is a common need, and Jenkins Pipeline gives you the tools to pull this off easily. Let's break down the implementation step by step.
Step 1: Track Failed Stage Details with Global Variables
First, define two global variables to store the name of the failed stage and its error logs. These variables will be updated whenever a stage fails, so we can reference them later in the final post block.
def failedStage = null def failedStageLogs = null
Step 2: Capture Failure Details in Each Stage
For every stage in your pipeline, add a post { failure } block (or use catchError if you want the pipeline to continue running after a stage failure) to update our global variables with the failed stage's name and logs.
Here's a complete pipeline example (extendable to your 5-6 stages):
pipeline { agent any stages { stage('Build Application') { steps { // Simulate a build failure for testing; replace with your actual build steps catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { sh 'echo "Running build..." && exit 1' } } post { failure { script { failedStage = env.STAGE_NAME // Grab the last 200 lines of build logs (adjust the number as needed) failedStageLogs = currentBuild.rawBuild.getLog(200).join('\n') } } } } stage('Run Unit Tests') { steps { catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { sh 'echo "Running tests..." && exit 1' } } post { failure { script { failedStage = env.STAGE_NAME failedStageLogs = currentBuild.rawBuild.getLog(200).join('\n') } } } } // Add your remaining stages (Deploy, Lint, etc.) following the same pattern } post { failure { mail to: 'team@example.com', subject: "Failed Pipeline: ${currentBuild.fullDisplayName} - Stage: ${failedStage}", body: """ Pipeline Failure Alert! ------------------------ Pipeline URL: ${env.BUILD_URL} Failed Stage: ${failedStage} Error Logs (Last 200 Lines): --------------------------- ${failedStageLogs} """ } } }
Key Notes:
catchErrorUsage: We usecatchErrorto mark the stage as failed but let the pipeline keep running (optional). If you want the pipeline to stop immediately after the first failed stage, removecatchError—the stage'spost { failure }block will still trigger and update the global variables.- Precise Log Capture: The
getLog(200)method fetches the last 200 lines of the build log, which covers most error contexts. For stage-specific logs (useful for long pipelines), you can use Jenkins' FlowNode API (requires admin script approval):failedStageLogs = currentBuild.rawBuild.getExecution() .getCurrentHeads()[0] .getFlowNodes() .find { it.getDisplayName() == failedStage } ?.getLog() ?.join('\n') - Script Block: All variable assignments and log fetching must be wrapped in a
scriptblock since we're using scripted syntax within a declarative pipeline.
Result
When your pipeline fails, the email will clearly state which stage failed and include the relevant error logs, making it far easier for your team to diagnose issues quickly.
内容的提问来源于stack exchange,提问作者Yash

