在Logstash中,如何使用json过滤器从日志事件中提取字段?

时间:2017-03-06 21:37:12

标签: logstash logstash-configuration

Logstash v2.4.1。

我正在通过UDP数据包将JSON格式的日志发送到我的Logstash服务器。日志看起来与此类似。

{
  "key1":"value1",
  "key2":"value2",
  "msg":"2017-03-02 INFO [com.company.app] Hello world"
}

这是我的输出过滤器

output {
  stdout {
    codec => rubydebug
  }
  file {
    path => "/var/log/trm/debug.log"
    codec => line { format => "%{msg}" }
  }
}

ruby​​debug输出编解码器显示如下的日志

{
  "message" => {\"key1\":\"value1\", "key2\":\"value2\", \"msg\":\"2017-03-02 INFO [com.company.app] Hello world\"
}

并且文件输出过滤器也正确显示JSON日志,如此

{"key1":"value1", "key2":"value2", "msg":"2017-03-02 INFO [com.company.app] Hello world"}

当我在输入过滤器中使用JSON代码时,我从“一些”日志中获取Logstash的_jsonparsefailures,即使不同的在线JSON解析器正确解析JSON,意味着我的日志采用有效的JSON格式

input {
  udp => {
    port => 5555
    codec => json
  }
}

因此,我正在尝试使用json过滤器,就像这样

filter {
  json => {
    source => "message"
  }
}

使用json过滤器,如何在“消息”中提取“key1”,“key2”和“msg”字段?

我试过这个无济于事,也就是说,我在rubydebug输出中看不到“key1”字段。

filter {
  json => {
    source => "message"
    add_field => {
      "key1" => "%{[message][key1]}"
    }
  }
}

1 个答案:

答案 0 :(得分:0)

我建议你从下面两个配置中的一个开始(我使用multiline编解码器将输入连接到一个json,因为否则logstash会逐行读取,而json的一行是不是有效的json),然后过滤json,或使用json编解码器,然后将其输出到需要的地方。你仍然会有一些配置要做,但我相信它可能会帮助你开始:

input{
  file {
     path => "/an/absolute/path/tt2.json" #It really has to be absolute!
     start_position => beginning
     sincedb_path => "/another/absolute/path" #Not mandatory, just for ease of testing

   codec =>   multiline{
    pattern => "\n"
        what => "next"

     }
  }
}

filter{
   json {
     source => "multiline"
   }
}
output {
  file {
    path => "data/log/trm/debug.log"
  }

 stdout{codec => json}
}

第二种可能性:

input{
  file {
    path => "/an/absolute/path/tt2.json" #It really has to be absolute!
         start_position => beginning
         sincedb_path => "/another/absolute/path" #Not mandatory, just for ease of testing

   codec =>   multiline{
    pattern => "\n"
        what => "next"

     }
   codec => json{}
  }
}


output {
  file {
    path => "data/log/trm/debug.log"
  }

 stdout{codec => json}
}

编辑使用udp输入我想它应该是(未测试):

input {
  udp => {
    port => 5555

   codec =>   multiline{ #not tested this part
    pattern => "^}"
        what => "previous"

     }
   codec => json{}
  }
}
相关问题