首页 文章

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

提问于
浏览
0

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}" }
  }
}

rubydebug输出编解码器显示这样的日志

{
  "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代码时,即使不同的在线JSON解析器正确解析JSON, meaning my logs are in a valid JSON format ,我也可以在"some"logs上从Logstash获取_jsonparsefailures .

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

    我建议你从下面的两个配置之一开始(我使用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}
    }
    

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

    input {
      udp => {
        port => 5555
    
       codec =>   multiline{ #not tested this part
        pattern => "^}"
            what => "previous"
    
         }
       codec => json{}
      }
    }
    

相关问题