Getting a specific string from job log - jenkins

I need some help. I'm a noob in Jenkins and Groovy.
How to get a specific string from the log containing a certain word and print?
def log = Jenkins.getInstance().getItemByFullName
('deploy/my_deploy').getBuildByNumber(checkjob.getNumber()).log
if (log.contains("Word")) {println log}

Not sure about the "log" type Jenkins sends back, but for instance you can try the findAll method, like this :
def log = [ "First line", "Second line", "End of log"]
println log.findAll { line -> line.contains("line") }
>>> [First line, Second line]
Which iterates through the string list (log), and for every line in it, take it if the condition ( line.containts("line") ) is true

Related

How can I force Jenkins Blue Ocean to display print output instead of "Print Message"?

In the below screenshot some debug entries display the output text (with - Print Message at the end) while others simply display Print Message. To view these you have to expand the step to see the output.
All lines are using the format print "TEXT HERE". I've tried using print, println, and echo. All have the same output.
Why do these sometimes display the message, while others force it into a collapsed section? Is it possible to configure this to always show? The normal non-Blue Ocean Jenkins interface displays fine but there is a lot of verbosity.
This seems to be a known issue:
https://issues.jenkins-ci.org/browse/JENKINS-53649
It looks like that BlueOcean does not handle the Groovy GStrings correctly. This is what I've observed:
A simple:
echo "hello world"
will work as expected and will display correctly.
Whereas a templated string with variables, like:
echo "hello ${some_variable}"
will hide the message under a "Print Message" dropdown.
See also this answer.
It appears that if echo uses a variable with value from params or environment (i.e. "params.*"), then step label gets "Print message" name instead of actual value being echoed. It does not matter if the variable itself is a String or not. Even explicitly converting the params value to String does not help.
String param_str
String text_var_2
parameters {
string(name: 'str_param', defaultValue: 'no value')
}
param_str = params.str_param.toString()
echo "string text in double quotes is ${param_str}"
echo "simple quoted string is here"
echo 'simple quoted string is here'
echo 'Single quoted with str ' + param_str + ' is here'
echo param_str
text_var_2 = 'Single quoted str ' + param_str + ' combined'
echo "GString global text2 is ${text_var_2}"
echo 'String global text2 is' + text_var_2
BlueOcean shows simple quoted strings in step label, but everything else as "Print message".
BlueOcean output
Note that 'normal' variables (strings, integers) are not included into this example, but they are also shown in the label normally. So if you have a code like this
def text_str = 'Some string'
def int_var = 1+2
echo text_str + ' is here'
echo int_var
These will be shown on the label.
And indeed it appears to be a known Jenkins issue as stated in a previous answer.
This is a known BlueOcean bug. The console output in the "classic" view interpolates variables correctly.
One workaround is to use the label parameter of the sh step:
def message = 'Hello World'
sh(script: "echo $message", label: message)
I tried lots of things and seems the moment an environment variable is going to be displayed, it uses Print Message instead the text.
Another workaround would be to split the multiline string into an array and iterate over it :-
String[] splitData = MULTI_LINE_STRING.split("\n");
for (String eachSplit : splitData) {
print(eachSplit);
}

How to print a line only if it contains a specific string using groovy?

I have a Jenkins log file and I want to print the lines that contain the string "FOUND" on it.
How to achieve that using Groovy?
You could do something like this and comments in-line.
//Change log file name in below statement
def lines = new File('/tmp/test123.txt').readLines()
//Get the list of matching lines
def result = lines.findAll { it.contains('FOUND') }
println result*.toString()

executing code dynamically in groovy

I am trying to run code dynamically in groovy. I have someNode[0], which is the value, in variable var1
I then added double quotes to it like this
var2 = "\""+var1+"\""
then I tried to run this
request.abc."$var2"=Value
I saw here that something of this sort can be done on properties and methods. But the above code is not working. Giving me error
An error occurred [Cannot set property '"someNode[0]"' on null object], see error log for details
Any help is appreciated. Thanks.
Edit
Heres a snippet of my request
{
"app":{
"bundle":"531323947",
"cat":[
"IAB1",
"IAB9",
"IAB9-30",
"entertainment",
"games"
],
"id":"agltb3B1Yi1pbmNyDAsSA0FwcBitsL4UDA",
.
.
The field I am trying to manipulate is cat[0], which is IAB1 (I just used abc and someNode[0] in the code that i wrote above but actually they are app and cat[0])
Also, I parsed the request with jsonslurper befor running the above code
Thank you for your help
One way to do this, is by Eval
def request =[
"app":[
"bundle":"531323947",
"cat":[
"IAB1",
"IAB9",
"IAB9-30",
"entertainment",
"games"
],
]
]
assert request.app.cat[0]=='IAB1'
def var = 'request.app.cat[0]'
Eval.me('request', request, "$var = 'new value'")
assert request.app.cat[0]=='new value'
You are accessing/updating values from a map and a list. The request.app node will be a map, the request.app.cat node will be a list. Getting and setting the values in a map can be done in many different ways:
Use the put & get methods directly.
Use brackets [].
Use missing properties as map keys (i.e. the way you are using it).
For what you want to achieve, i.e. to access values from variable keys, it is much easier to use method 1 or 2 instead of method 3 with a variable inside a GString.
Example using brackets:
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def request = new JsonSlurper().parseText '''{
"app":{
"bundle":"531323947",
"cat":[
"IAB1",
"IAB9",
"IAB9-30",
"entertainment",
"games"
],
"id":"agltb3B1Yi1pbmNyDAsSA0FwcBitsL4UDA"
}
}'''
def level0 = 'app'
def level1 = 'cat'
def node = request[level0][level1]
assert request instanceof Map
assert node instanceof List
assert node[0] == 'IAB1'
node[0] = 'new value'
assert node[0] == 'new value'
println new JsonBuilder(request).toPrettyString()
Output:
{
"app": {
"cat": [
"new value",
"IAB9",
"IAB9-30",
"entertainment",
"games"
],
"id": "agltb3B1Yi1pbmNyDAsSA0FwcBitsL4UDA",
"bundle": "531323947"
}
}

Cannot access params map using Groovy

I want little help which I suspect is due to my lack of understanding for Groovy syntax. So, here's the thing:
On the GSP page I want to set a field's value from the params map which is
["id":"107901", "Field_10.value":"2", "Field_10":["value":"2"],"Field_11.value":"", "Field_11":["value":""],action:'abc']
On the gsp page, I want to find the value against the key Field_{some-id}.value
So I am calling a tag like, g.testTag(id:field.id) with its implementation as
def testTag = { attrs,body->
println "params are ${params}"
def result = ""
def keyRequired = "Field_${attrs.id}.value"
println "keyRequired >>>>> ${keyRequired.toString()}"
params.each { key,value->
println "key is ${key}"
println "Value is ${value}"
if (key.equals(keyRequired.toString())) {
result = params.value
}
}
println "Final result is >>>>>> ${result}"
}
The value passed in id is 10 and with my params printed as above, I was expecting a value
of 2 which is corresponding to the key in the params to show up. But apparently I see the
result as null..
What am I doing wrong ? Can anyone help please...
Thanks
Not result = params.value, but result = value.
You have to change the line:
result = params.value
to:
result = value
At the each loop, you're basically saying that inside the params iteration, you're naming every key "key" and every value "value". So, params.value will actually look for the key value inside your params map, which is null.
Funny that you do that right with key but not with value. Probably just got distracted.
it is likely what you want to do, the groovy way (no need to loop over the keys of the map) to access "Field_10.value":"2"
result=params["Field_${attrs.id}.value"]
Alternatively, this also works because you have "Field_10":["value":"2"] in your map
result=params["Field_${attrs.id}"].value

Grails: How do I print in the cmd console?

I wanna print a few values in the console, how do I do this?
Every time I get into a function, I want it to print a line with whatever text, I just wanna know if I'm getting into the function, and for some if-else statements.
Mostly for debugging.
If you mean "print to the console output panel", then you simply need to use println:
println "Hello, world"
Results in printed output:
groovy> println "Hello, world"
Hello, world
If that's not what you mean, can you clarify your question to be more specific?
you might want to consider grails built in logging functionality which provides the same functionality as println plus more
http://grails.github.io/grails-doc/3.0.x/guide/single.html#logging
in your app just say
log.info "Hello World"
to print something everytime you enter an action in a controller you can do something like this
class UserController {
def beforeInterceptor = {
log.info "Entering Action ${actionUri}"
}
def index = {
}
def listContributors = {
}
}
this will print out to the log whenever the controller methods are entered because of the controller interceptor
The regular java System.out.println("Your stuff"); works too.

Resources