How to refer the value of variable in code block inside add_field?


(Saket Kumar) #1

ruby {
code => "

		filename = File.basename(event['path'], '.*')
		value = filename.split('_')
		x = value[0]
		y = value[1]+'_' + value[2] +'_'+ value[3]
		z = value[4]
	
	  "
	
add_field => { 
		"Test_Id" => "%{x}"
		"Run_Id" => "%{y}"
		"URL" => "%{z}"
	     }		

I tried above but no luck. Test_Id gets assigned to %{x} instead value of 'x'. same observed for Run_Id & URL.


(Magnus B├Ąck) #2

In your example, x, y, and z are local variables in the Ruby code snippet. They won't be visible to the outside unless you assign the values to Logstash fields, for example like this:

event['x'] = value[0]
event['y'] = value[1] + '_' + value[2] + '_' + value[3]
event['z'] = value[4]

But again, you're overcomplicating things. As I said yesterday this is a perfect job for grok. Something like this should work (depending on exactly what the input looks like and exactly what you expect to get from it):

filter {
  grok {
    match => [
      "path",
      ".*/(?<Test_Id>[^/_]+)_(?<Run_Id>[^/]+)_%(?<URL>[^/]+)
    ]
  }
}

(Saket Kumar) #3

Thanks magnus!


(system) #4