简体   繁体   中英

Ruby - getting value in logstash

i have a field and value output looks like

A::field_1_2_3_4_22_5_6_7_8_365  => 6

because the field name is "dynamical" because of contain ip and port. how to using ruby to get value from field name and add field for it ? it's will be looks like

A::field => 6
bIP => 1.2.3.4
bport => 22
cIP => 5.6.7.8
cport => 365

any help will be appreciated!!thanks

Here is an answer for a very similar question: logstash name fields dynamically

For this precise case, the ruby filter needs to be a bit more involved in order to capture different things

filter {
  ruby {
    code => "
      newhash = {}
      event.to_hash.each {|key, value| 
        re = /(\w::[a-z]+)_(\d+_\d+_\d+_\d+)_(\d+)_(\d+_\d+_\d+_\d+)_(\d+)/
        if key =~ re then
            field, bIP, bport, cIP, cport = key.match(re).captures
            newhash[field] = event[key]
            newhash['bIP'] = bIP.gsub('_', '.')
            newhash['bport'] = bport
            newhash['cIP'] = cIP.gsub('_', '.')
            newhash['cport'] = cport

            event.remove(key)
        end
      }
      newhash.each {|key,value|
        event[key] = value
      }
    "
  }
}

So if you have a field like "A::field_1_2_3_4_22_5_6_7_8_365" => "6" in your event, your event will then contain the following fields:

{
      "A::field" => "6",
           "bIP" => "1.2.3.4",
         "bport" => "22",
           "cIP" => "5.6.7.8",
         "cport" => "365"
}

You can use the the following code:

field_name = 'A::field_1_2_3_4_22_5_6_7_8_365'
fields = field_name.split("_")
bID = "#{fields[1]}.#{fields[2]}.#{fields[3]}.#{fields[4]}"
bport = "#{fields[5]}"
bID = "#{fields[6]}.#{fields[7]}.#{fields[8]}.#{fields[9]}"
bport = "#{fields[10]}"

Maybe i've not understooden this quite correctly but you can use arrays and method .push for adding:

Array=[1, 2, 5, 7]
@n = [3, 4, 6]
Array.push(@n) => Array=[1, 2, 3, 4, 5, 6, 7]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM