Here’s a short tip describing how to access to a pipeline job’s own Jenkins console log. You may need it for whatever purpose, whether it is archiving the logs along with the created artifact or taking any build decision after analyzing the logs.
stage('save log build') {
steps {
script {
def logContent = Jenkins.getInstance()
.getItemByFullName(env.JOB_NAME)
.getBuildByNumber(
Integer.parseInt(env.BUILD_NUMBER))
.logFile.text
// copy the log in the job's own workspace
writeFile file: "buildlog.txt", text: logContent
}
}
}
Simple isn’t it ? Well… Wait a minute, there are caveats:
- it seems like this must be done on a specific “stage” of it’s own, otherwise Jenkins may not have flushed all the logs to the file.
- This uses “risky” groovy so once you wrote it, you have to go a few times to the “in-script process approval” config screen to approve some method signature. Yes, this is unsafe as it opens the door to attacks on your Jenkins instance. But when it’s not Internet facing, the risk may be worth it. You decide.
The good part is that it (seem to) works (at least for now) whether run from the Jenkins master or a slave.
That’s it for today !
The File is not at all readable.It has all encoding stuff. Do u have suggestion to get a readable console out put as a text file?
Can you copy-paste here a sample of what you call “all the encoding stuff” please ? As I remember, mine had no specific encoding issues.
This solution throwing error env. is not accessible i ngroovy script
strange… Maybe they changed the syntax but a little search should bring you plenty ot exemples using ‘env’ in Jenkins pipelines.
Log into Jenkins and take a look at the bottom of the webpage near the right hand side and click on the REST API link. This will give you information about the Jenkins RESTful API which is a great way to pull information off of Jenkins once you understand how to construct the URL.
Source: https://stackoverflow.com/questions/24176033/how-to-get-jenkins-console-output-after-triggering-build-remotely
how can you just access only the log of a particular stage within the pipeline using the above syntax? for example one of my stages is called ‘Test’ and I want just that log to be written into the txt file.
I don’t know any easy solution. One very dirty workaroud would be to get the log text BEFORE your ‘test’ stage and then also AFTER and to deduce that only new lines were created by the ‘test’ stage. I think this would work despite not being very elegant !