如何在Jenkinsfile中用BUILD_LOG_REGEX格式化匹配行实现换行
解决Jenkins emailext多匹配项换行问题
方案1:利用HTML换行符(推荐,适用于默认HTML邮件)
Jenkins的emailext默认发送HTML格式邮件,普通换行符\n不会被解析,需用HTML的换行标签<br>。修改BUILD_LOG_REGEX的substText,在每个匹配项后添加<br>:
${BUILD_LOG_REGEX, regex="(^.*Check out job at.*)", showTruncatedLines="false", substText="Access the test recording here: \$1<br>"}
- 用括号
()把整个匹配内容作为捕获组$1,在替换文本后追加<br>,每个匹配项就会单独占一行。
方案2:提前用Groovy脚本处理日志内容
如果方案1不生效,可在Jenkinsfile中先提取并格式化日志内容,再在邮件中引用变量:
// 在pipeline的stage或post块中添加以下代码 def testRecordingLines = [] // 获取构建日志(此处取最后2000行,可根据需求调整行数) currentBuild.rawBuild.getLog(2000).each { line -> if (line ==~ /^.*Check out job at/) { testRecordingLines.add("Access the test recording here: ${line}") } } // 用HTML换行符拼接所有行 def formattedRecordings = testRecordingLines.join('<br>') // 然后在emailext中引用变量 emailext( subject: '自动化测试结果', body: """ 测试记录:<br> ${formattedRecordings} """, to: 'xxx@example.com' )
方案3:切换为纯文本邮件(若需纯文本格式)
如果需要发送纯文本邮件,需指定contentType为text/plain,此时\n会生效:
emailext( subject: '自动化测试结果', body: """ 测试记录: ${BUILD_LOG_REGEX, regex="^.*Check out job at", showTruncatedLines="false", substText=" Access the test recording here:\n"} """, to: 'xxx@example.com', mimeType: 'text/plain' )
内容的提问来源于stack exchange,提问作者Jyoti
相关产品推荐
相关产品推荐

