「Jenkins Pipeline」- 使控制台彩色化输出(使用 AnsiColor 插件) @20210415

问题描述

在 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


posted @ 2021-04-15 19:50  研究林纳斯写的  阅读(1190)  评论(0编辑  收藏  举报