How add Reporter.log() to log on Jenkins? - jenkins

How can I add Reporter.log() on Jenkins log?
I write my test in java and used TestNG.
I try import:
import org.testng.Reporter;
next write method:
Reporter.log("Click on button next");
click(btnNext);
return this;
}
and write test:
public void shouldPageChangeAfterClick(){
mainPage
.launch()
.clickOnBtnNextPage()
.assertThatPageIsCorrect();
}
Next I run test on Jenkins from pom.xml, test is failed, but I don't see Reporter.log() in log on Jenkins.
What should I do to display Reporte.log() on Jenkins?

Reporter.log() method is to log the passed string to the HTML report. It will not print in any console or log file. You have to use different logger api to get the same in Jenkins console. Log4j will be helpful in this case.

Related

Log messages are not showing up in groovy jenkins script

I'm in need to extend my jenkins scripts with logging functionality and tried to use java.util.logging for this purpose. The following snippet shows what I already did.
import java.util.logging.*
#NonCPS
def tryLogging() {
println("Start")
Logger logger = Logger.getLogger("Test")
logger.setLevel(Level.INFO);
logger.setUseParentHandlers(false);
ConsoleHandler handler = new java.util.logging.ConsoleHandler()
handler.setFormatter(new SimpleFormatter())
logger.addHandler(handler)
logger.info("Hello")
logger.severe("Severe")
println("End")
}
tryLogging()
My console log now says the following:
[Pipeline] Start of Pipeline
[Pipeline] echo
Start
[Pipeline] echo
End
There is really no visible log message and I don't know, what I'm doing wrong. Can anyone here explain me how to make the console log visible? I'm also unsure if I have to use this #NonCPS here?
[Pipeline] End of Pipeline
Finished: SUCCESS
ConsoleHandler prints to System.err. Modify your script to use
System.err.println("Start") and see if 'Start' still shows up in the console. If it doesn't then the problem is the ConsoleHandler is writing to a stream you can't see.
Another thing to change is that you'll want to ensure your named logger can't be garbage collected. Depending the Java version you are using the logger can be garbage collected and you can lose your attached handler.
I'm also unsure if I have to use this #NonCPS here?
What is #NonCPS annotation in Jenkins pipeline script has information that you might find helpful.

How to run groovy script to read build cause?

I am writing a first groovy script in the Jenkins, have an upstream job A which calls job B.
Being in job B I need to read GERRIT_CHANGE_NUMBER which triggered the job A.
In below e.g, how to get 28331 in the downstream job B?, its printed in the job B's console as below:
Started by upstream project some_up_project build number 100
originally caused by:
Triggered by Gerrit: https://gerrit-server.com/28331
I looked at this SO answer, but not sure how to do this in jenkins.
In job B, I did Add build step to add Execute system Groovy script section, then chose Groovy command in its dropdown, and in the Groovy Script area, added below for testing purpose, it gives error as unable to resolve class Run.cause ..., tried many other ways too and nothing worked.
import hudson.model.Run
for (cause in Run.getCauses()) {
if (cause instanceof Run.Cause.UserIdCause) {
println cause.getUserName()
}
}
there is no such class Run.Cause
start from something that works: hudson.model.Run
search for the documentation: hudson.model.Run.getCauses()
the method returns: List<Cause>
so, import this class into your code and use it:
import hudson.model.Cause
import hudson.model.Run
for (cause in Run.getCauses()) {
if (cause instanceof Cause.UserIdCause) {
println cause.getUserName()
}
}
Note: I have not tested the code. I just gave you an idea how to resolve an error.

How to pass pipeline variables to post build gerrit message?

I have a Pylint running in a Jenkins pipeline. To implement it, I used Gerrit trigger plugin and Next Generation Warnings plugin. Everything is working as expected - Jenkins is joining the review, checks change with pylint and generates report.
Now, I'd like to post pylint score in a custom "Build successful" message. I wanted to pass the pylint score to a environment variable and use it in dedicated window for Gerrit plugin message.
Unfortunately no matter what I try, I cannot pass any "new" variable to the message. Passing parameters embedded in pipeline works (e.g. patchset number).
I created new environment variable in Configure Jenkins menu, tried exporting to shell, writing to it (via $VAR and env. syntax) but nothing works - that is, build message displays raw string like $VAR instead of what variable contains.
What should I do to pass local pylint score (distinct for every pipeline occurence) to the custom build message for Gerrit?
I don't think the custom message can be used for this. This is just supposed to be a static message.
They way I do this is to use the SSH command to perform the review. You can also achieve the same using the REST API.
First I run my linting and white space checking script that will generate a json file with the information I would like to pass to Gerrit. Next I send it to Gerrit using SSH. See below my pipeline script and an example json file.
As a bonus I have added the robot comments. This will now show up in your review as a remark from Jenkins that line 8 of my Jenkins file has a trailing white space. You can easily replace this with your lint result of you like or just ignore it and only put the message. It is easier to use a json file as it will make it easier to create multi line messages
node('master') {
sh """
cat lint_change.json | ssh -p ${env.GERRIT_PORT} ${env.GERRIT_HOST} gerrit review ${env.GERRIT_PATCHSET_REVISION} --json
"""
}
Example json file:
{
"labels": {
"Code-Style": "-1"
},
"message": "Lint Bot Review\nLint Results:\n Errors: 0\n Warnings: 0\n\nWhitespace results:\n Errors: 1",
"robot_comments": {
"Jenkinsfile": [
{
"robot_id": "lint-bot",
"line": "8",
"message": "trailing whitespace."
}
]
}
}
Alternatively, you may want to look at a new gerrit-code-review-plugin that should make this things even easier. However, I have not tried this yet.

What is required to display custom messages in jenkins report?

I have Jenkins ver. 2.7.4 and I want to see custom messages in report
besides stack trace. What do I need to do for this?
If you are writing a jenkins plugin and you've subclassed Notifier, then you can log to the build output using an instance of BuildListener, like so:
Helper method:
private void logger(BuildListener listener, String message){
listener.getLogger().println(message);
}
Example Usage:
logger(listener, "Verbose Logging Enabled");
You can see a real world example of this in the source code for the packagecloud plugin for jenkins
See: https://wiki.jenkins-ci.org/display/JENKINS/Packagecloud+Plugin

Not able to run parameter passed methods in jenkins

i am using java with selenium , maven, testng for my project.
for some functions , i have passed parameters through testng parameters annotations.
while build and executing the project through jenkins,
parameter passed methods are not executed through jenkins.
other methods are executed fine.
Please provide solutions. Awaiting the response
sample code
#Test(priority=1)
#Parameters({"drivername","driverpath","outputpath","URL"})
public void opendriver(#Optional("drivername") String drivername,#Optional("driverpath") String driverpath,#Optional("outputpath") String outputpath,#Optional("URL") String URL)
in the above code i have passed some parameters through testng. while executing the code
through maven it is working fine. but making build in jenkins and execute the script
it is not working. Please suggest and advise

Resources