alabaster alabaster -4 years ago 186
JSON Question

Pretty-print JSON document in Logstash 5

I am using Logstash 5 to ingest a file containing a set of JSON documents, extract part of each document in each event, and write them out to another file.

I want to pretty-print the output JSON. I found this thread: How do I pretty-print JSON for an email body in logstash? which looked ideal, but Logstash 5 now prevents you from accessing event attributes directly, replacing it with event.get and event.set methods (see https://www.elastic.co/guide/en/logstash/current/event-api.html).

I tried to convert the above as follows:

ruby {
init => "require 'json'"
code => "@pretty_body = JSON.pretty_generate(event.get('body'))
event.set('body', @pretty_body)
"
}


but get

ERROR logstash.filters.ruby - Ruby exception occurred: only generation of JSON objects or arrays allowed


What is the correct LS5 equivalent of the above?

Answer Source

I think you're looking for the following:

filter {
  ruby  {
    init => "require 'json'"
    code => "event.set('message', JSON.pretty_generate(JSON.parse(event.get('message'))))"
  }
}

Here is my test and the result:

input: {"make_me_pretty":"test"}
{
    "@timestamp" => 2017-03-22T04:56:00.118Z,
      "@version" => "1",
       "message" => "{\n  \"make_me_pretty\": \"test\"\n}"
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download