問題描述
在 Jenkins Pipeline 中,執行 npm 命令所產生的輸出日志,包含大量 ANSI 轉義序列,這些轉義序列無法被解析並且會影響日志的可讀性。另外有些時候,我們也希望可以在輸出中顯示彩色日志消息。
本文將介紹如何使用插件,使 Jenkins 的控制台能夠解析 ANSI 轉義序列,產生彩色化輸出。
解決方法
安裝 AnsiColor 插件,該插件可以解析在 Console Output 中 ANSI 轉義序列輸出。,在控制台中產生彩色輸出。
倉庫地址:jenkinsci/ansicolor-plugin: Jenkins ANSI Color Plugin
使用手冊:https://jenkins.io/doc/pipeline/steps/ansicolor/
使用方法
安裝及配置
安裝過程與其他插件類似,這里不再贅述。
安裝結束后,需要在 Manage Jenkins => Configure System => ANSI Color => Advanced... 中定義配色方案,后面要用到這個名稱。
使用方法(在 Jenkins Pipeline 中)
wrap([$class: 'AnsiColorBuildWrapper', 'colorMapName': 'xterm']) { sh 'something that outputs ansi colored stuff' } ansiColor('xterm') { echo 'something that outputs ansi colored stuff' } // 當然,你的輸出中要包含ANSI轉義序列才行,否則無法產生彩色輸出。 // 上面代碼中並未包含轉義序列
上面的 xterm 既是之前配置的配色方案的名稱。
附加說明
在普通作業中使用
該插件也可以在普通JOB中使用,詳細可以參考「AnsiColor」插件主頁。
現存問題
在 Jenkins 2.182 中,對於如下代碼:
pipeline { agent any stages { // 顯示環境相關的信息 stage('example') { steps { script { ansiColor("xterm") { echo "\u001B[31mPurple\u001B[0m" stage "\u001B[31mI'm Red\u001B[0m Now not" } } } } } }
有時能夠產生紅色輸出,有時不能產生紅色輸出。在經過一些嘗試后發現,在輸出過程中會出現轉義字符,但是刷新頁面就變成彩色內容。
相關文章
「Jenkins Pipeline」- 常用 JSON 操作
「Jenkins」- 發送 Jabber (XMPP) 通知
「Jenkins Pipeline」- 配置多版本NodeJS構建環境
「Jenkins Pipeline」- 發送郵件
「Jenkins Pipeline」- 接受構建通知,並拉取代碼
「Jenkins Pipeline」- 憑證的處理
「Jenkins Pipeline」- 暫存文件,以用於之后的構建
參考文獻
Jenkins/Plugins/AnsiColor
pipeline-examples/pipeline-examples/ansi-color-build-wrapper/AnsiColorBuildWrapper.groovy