【问题标题】:How do I parse JSON log file with jq?如何使用 jq 解析 JSON 日志文件?
【发布时间】:2019-12-01 20:41:47
【问题描述】:

我在 JSON 日志文件中有两种类型的日志,我想使用 jq 过滤器来解析和标记每个事件。下面是每个事件的示例:

目标是标记每个事件,以便如果消息以 TR 开头,则 .sourcetype=application_log,否则如果消息以 IP 开头,则 .sourcetype=access_log。

到目前为止,我正在处理这个:test.log jq -r '.[] |选择(.log[12:14] == "TR") | .sourcetype = "application_log" | .sourcetype'

{
"log": "{\"message\":\"TR=failed to send order confirmation to \\\"someone@example.com\\\": rpc error: code = Unavailable desc = all SubConns are in TransientFailure, latest connection error: connection error: desc = \\\"transport: Error while dialing dial tcp 10.64.5.235:5000: i/o timeout\\\"\",\"severity\":\"warning\",\"timestamp\":\"2019-07-23T00:47:07.216693578Z\"}\n",
"stream": "stdout",
"time": "2019-07-23T00:47:07.222368843Z"
}

{
"log": "{\"message\":\"IP=failed to send order confirmation to \\\"someone@example.com\\\": rpc error: code = Unavailable desc = all SubConns are in TransientFailure, latest connection error: connection error: desc = \\\"transport: Error while dialing dial tcp 10.64.5.235:5000: i/o timeout\\\"\",\"severity\":\"warning\",\"timestamp\":\"2019-07-23T00:47:07.216693578Z\"}\n",
"stream": "stdout",
"time": "2019-07-23T00:47:07.222368843Z"
}

【问题讨论】:

标签: json filter jq


【解决方案1】:

如果我正确理解任务,解决方案是:

.log[12:14] as $code    
| if ($code == "TR") then .sourcetype = "application_log"
  elif ($code == "IP") then .sourcetype = "access_log"
  else .
  end

如果您希望将 .log 值作为 JSON 对象,以便在其中添加 .sourcetype,则必须在原始 .log 值上使用 fromjson,如下所示:

.log |= fromjson
| .message[0:2] as $code    
| if ($code == "TR") then .log.sourcetype = "application_log"
  elif ($code == "IP") then .log.sourcetype = "access_log"
  else .
  end
| .log |= tostring . # is this line really needed?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    相关资源
    最近更新 更多