【问题标题】:How do I parse a json-formatted log message in Logstash to get a certain key/value pair?如何在 Logstash 中解析 json 格式的日志消息以获取某个键/值对?
【发布时间】:2016-09-01 21:24:43
【问题描述】:

我将 json 格式的日志发送到我的 Logstash 服务器。日志看起来像这样(注意:整个消息实际上是在一行中,但我将其显示为多行以方便阅读)

2016-09-01T21:07:30.152Z 153.65.199.92 
{ 
  "type":"trm-system",
  "host":"susralcent09",
  "timestamp":"2016-09-01T17:17:35.018470-04:00",
  "@version":"1",
  "customer":"cf_cim",
  "role":"app_server",
  "sourcefile":"/usr/share/tomcat/dist/logs/trm-system.log",
  "message":"some message"
}

我需要在我的 Logstash 配置中添加什么来获取“sourcefile”值并最终获取文件名,例如 trm-system.log?

【问题讨论】:

    标签: logstash logstash-configuration


    【解决方案1】:

    如果你将哈希字段(没有时间戳)注入到 ES 中,它应该能够识别它。

    如果您想在 logstash 管道中执行此操作,您可以使用 json filter 并将 source => 指向该行的第二部分(可能会添加时间戳前缀)。

    这会导致所有字段都添加到当前消息中,您可以直接访问它们或将它们全部组合起来:

    配置:

    input { stdin { } }
    filter {
      # split line in Timestamp and Json
      grok { match => [ message , "%{NOTSPACE:ts} %{NOTSPACE:ip} %{GREEDYDATA:js}"] }
    
      # parse json part (called "js") and add new field from above
      json { source => "js" }
    }
    output { 
      # stdout { codec => rubydebug }
      # you access fields directly with %{fieldname}:
      stdout { codec => line { format => "sourcefile: %{sourcefile}"} }
    }
    

    示例运行

    2016-09-01T21:07:30.152Z 153.65.199.92 { "sourcefile":"/usr" }
    sourcefile: /usr
    

    并使用 ruby​​debug(主机和 @timestamp 已删除):

    {
       "message" => "2016-09-01T21:07:30.152Z 153.65.199.92 { \"sourcefile\":\"/usr\" }",
      "@version" => "1",
            "ts" => "2016-09-01T21:07:30.152Z",
            "ip" => "153.65.199.92",
            "js" => "{ \"sourcefile\":\"/usr\" }",
    "sourcefile" => "/usr"
    }
    

    如您所见,sourcefile 字段直接与 ruby​​debug 输出中的值有关。

    根据日志记录的来源,您可能还需要使用multiline 编解码器。您可能还想删除 js 字段,将 @timestamp 重命名为 _parsedate 并将 ts 解析为记录时间戳(让 Kibana 开心)。这未在示例中显示。我还会删除 message 以节省空间。

    【讨论】:

    • 我想在 Logstash 管道中解析它,因为我想在输出插件中使用文件名。我查看了 json 过滤器,但文档没有解释如何获取某个字段及其值。请详细说明您的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    相关资源
    最近更新 更多