Skip to content

Instantly share code, notes, and snippets.

@mucst
Last active August 23, 2024 18:43
Show Gist options
  • Save mucst/35c3603aaf36becd2d6722696afb8e0a to your computer and use it in GitHub Desktop.
Save mucst/35c3603aaf36becd2d6722696afb8e0a to your computer and use it in GitHub Desktop.
How to println to console log from jenkins shared library class
/*
* If you develop a jenkins shared library, you might eventually face the issue described at:
* https://stackoverflow.com/questions/47320406/propagating-logs-in-shared-library-to-jenkins-job-console
*
* Many across the internet suggest to pass the "steps" object to the class as some (constructor) parameter, such as in
* https://www.jenkins.io/doc/book/pipeline/shared-libraries/#accessing-steps
*
* ... which works, however this might be difficult if there are many usages of the class where you "just" want to print something to
* the console, maybe just for some debugging purposes. Unfortunatelly standard java Logger (in the momemnt of writing this gist at least)
* does not work. A not so nice, however working solution can be the following.
*/
// create a Utility class with a static Closure called "log":
class JenkinsUtils {
static Closure<Void> log = { throw new RuntimeException("Logger not configured") }
}
// then, in your pipeline script you assign a sensible valie to it. You should do this in a @NonCPS block (see google for the reason).
// jenkins.groovy:
@NonCPS
def setupLogging() {
JenkinsUtils.log = { String msg-> println msg }
}
def call() {
...
setupLogging()
...
}
// then, in your widely used shared library class you can use this static closure without further ado:
class RestClient {
void doStuff() {
JenkinsUtils.log("...")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment