Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logstash grok filter - name fields dynamically

Tags:

logstash

I've got log lines in the following format and want to extract fields:

[field1: content1] [field2: content2] [field3: content3] ...

I neither know the field names, nor the number of fields.

I tried it with backreferences and the sprintf format but got no results:

match => [ "message", "(?:\[(\w+): %{DATA:\k<-1>}\])+" ] # not working
match => [ "message", "(?:\[%{WORD:fieldname}: %{DATA:%{fieldname}}\])+" ] # not working

This seems to work for only one field but not more:

match => [ "message", "(?:\[%{WORD:field}: %{DATA:content}\] ?)+" ]
add_field => { "%{field}" => "%{content}" }

The kv filter is also not appropriate because the content of the fields may contain whitespaces.

Is there any plugin / strategy to fix this problem?

like image 942
Cipher Avatar asked Jul 07 '14 07:07

Cipher


2 Answers

Logstash Ruby Plugin can help you. :)

Here is the configuration:

input {
    stdin {}
}

filter {
    ruby {
        code => "
            fieldArray = event['message'].split('] [')
            for field in fieldArray
                field = field.delete '['
                field = field.delete ']'
                result = field.split(': ')
                event[result[0]] = result[1]
            end
        "
    }
}

output {
    stdout {
        codec => rubydebug
    }
}

With your logs:

[field1: content1] [field2: content2] [field3: content3]

This is the output:

{
   "message" => "[field1: content1] [field2: content2] [field3: content3]",
  "@version" => "1",
"@timestamp" => "2014-07-07T08:49:28.543Z",
      "host" => "abc",
    "field1" => "content1",
    "field2" => "content2",
    "field3" => "content3"
}

I have try with 4 fields, it also works.

Please note that the event in the ruby code is logstash event. You can use it to get all your event field such as message, @timestamp etc.

Enjoy it!!!

like image 76
Ben Lim Avatar answered Oct 21 '22 16:10

Ben Lim


I found another way using regex:

ruby {
    code => "
        fields = event['message'].scan(/(?<=\[)\w+: .*?(?=\](?: |$))/)
        for field in fields
            field = field.split(': ')
            event[field[0]] = field[1]
        end
    "
}
like image 42
Cipher Avatar answered Oct 21 '22 15:10

Cipher