logstash配置中的负正则表达式

时间:2014-02-26 05:44:09

标签: logstash

我无法在LogStash中使用负面的regexp表达式(如the docs中所述)

考虑以下正面正则表达式,它可以正确检测已分配值的字段:

if [remote_ip] =~ /(.+)/ {
    mutate { add_tag => ["ip"] }
}

但是,即使字段为空,否定表达似乎返回false:

if [remote_ip] !~ /(.+)/ {
    mutate { add_tag => ["no_ip"] }
}

我误解了用法吗?

更新 - 这对我来说是模糊的思考。我的配置文件存在问题。如果你的配置文件的其余部分是理智的,那么上面应该可行。

2 个答案:

答案 0 :(得分:2)

这对我来说是模糊的思考 - 我的配置文件的其余部分存在问题。

根据Ben Lim的例子,我提出了一个更容易测试的输入:

input {
    stdin { }
}

filter {
    if [message] !~ /(.+)/ {
         mutate { add_tag => ["blank_message"] }
    }
    if [noexist] !~ /(.+)/ {
         mutate { add_tag => ["tag_does_not_exist"] }
    }
}

output {
    stdout {debug => true}
}

空白消息的输出为:

{
       "message" => "",
      "@version" => "1",
    "@timestamp" => "2014-02-27T01:33:19.285Z",
          "host" => "benchmark.example.com",
          "tags" => [
        [0] "blank_message",
        [1] "tag_does_not_exist"
    ]
}

内容为“测试消息”的消息的输出为:

test message
{
       "message" => "test message",
      "@version" => "1",
    "@timestamp" => "2014-02-27T01:33:25.059Z",
          "host" => "benchmark.example.com",
          "tags" => [
        [0] "tag_does_not_exist"
    ]
}

因此,只有当字段为空或字段不存在时,“否定正则表达式”/(.+)/才会返回true。

否定正则表达式/(.*)/仅在该字段不存在时才返回true。如果该字段存在(无论是空还是带有值),则返回值将为false。

答案 1 :(得分:1)

以下是我的配置。类型字段不存在,因此,否定表达式返回true。

input {
    stdin {
    }
}

filter {
    if [type] !~ /(.+)/ {
         mutate { add_tag => ["aa"] }
    }
}

output {
    stdout {debug => true}
}

正则表达式 /(。+)/ 表示它接受所有内容,包括空白。因此,当“类型”字段存在时,即使字段值为空,它也符合正则表达式。因此,在您的示例中,如果remote_ip字段存在,则您的“否定表达式”将始终返回false。

相关问题