Reputation: 1357
I defined a quick logger in my pipeline to test the colored logs with AnsiColor plugin.
It works like a charm.
def logger(String str, String level)
{
if (level == "ALERT")
{
ansiColor('xterm')
{
echo '\033[32m' + str // Green
}
}
else if (level == "BOLD")
{
ansiColor('xterm')
{
echo '\033[1;31m' + str // Green
}
}
}
I call it then
logger("CHECK THIS ALERT","ALERT")
and it prints:
Now the problem is that I want to move this method in a class in our shared libraries (we already have some other share libs working with no issues)
But when I move the method under the shared lib class the below issue:
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: com.pipeline.Logger.ansiColor() is applicable for argument types: (java.lang.String, org.jenkinsci.plugins.workflow.cps.CpsClosure2) values: [xterm, org.jenkinsci.plugins.workflow.cps.CpsClosure2@a2e9a55]
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:54)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.methodCall(DefaultInvoker.java:20)
I think this is an issue of visibility so that the shared Library does not have visibility of the ansiColor() method, but I'm not sure how to import it, with the DSL plugin we deal with those issues through the delegate usage, but as far I know they are not usable within the pipelines.
Upvotes: 1
Views: 1736
Reputation: 2976
I have a similar class that I use in my shared libraries. I think that what you're missing is the "pipeline" object. Your class should look like:
class MyLogger implements Serializable {
static void logger(Script pipelineScript, String str, String level){
if (level == "ALERT"){
pipelineScript.ansiColor('xterm'){
pipelineScript.echo '\033[32m' + str // Green
}
}
else if (level == "BOLD"){
pipelineScript.ansiColor('xterm'){
pipelineScript.echo '\033[1;31m' + str // Green
}
}
}
}
Then call it from you Jenkinsfile:
Mylogger.logger(this, "CHECK THIS ALERT","ALERT")
My implementation looks like this:
class MyLogger implements Serializable {
static void printError(Script script, String message) {
script.echo "\u001B[1;31m [ERROR] ${message} \u001B[0m"
}
static void printInfo(Script script, String message) {
script.echo "\u001B[1;34m [INFO] ${message} \u001B[0m"
}
static void printWarn(Script script, String message) {
script.echo "\u001B[1;33m [INFO] ${message} \u001B[0m"
}
}
And then the usage from the Jenkinsfile is:
ConsoleLogger.printInfo(this,"This is an info")
ConsoleLogger.printWarn(this,"This is a warning")
ConsoleLogger.printError(this,"This is an error")
Upvotes: 2