title: How do I pretty-print JSON for an email body in logstash?
body: <p>I have a Logstash configuration that I've been using to forward log messages in emails. It uses <code>json</code> and <code>json_encode</code> to parse and re-encode JSON log messages.</p>
  
  <p><code>json_encode</code> used to pretty-print the JSON, which made for very nice looking emails. Unfortunately, with recent Logstash upgrades, it no longer pretty prints.</p>
  
  <p>Is there any way I can get a pretty form of the event into a field that I can use for the email bodies? I'm fine with JSON, Ruby debug, or most other human readable formats.</p>
  
  <pre><code>filter {
      if [type] == "bunyan" {
          # Save a copy of the message, in case we need to pretty-print later
          mutate {
              add_field =&gt; { "@orig_message" =&gt; "%{message}" }
          }
  
          json {
              source =&gt; "message"
              add_tag =&gt; "json"
          }
      }
  
      // other filters that might add an "email" tag
  
      if "email" in [tags] {
          # pretty-print JSON for the email
          if "json" in [tags] {
              # re-parse the message into a field we can encode
              json {
                  source =&gt; "@orig_message"
                  target =&gt; "body"
              }
  
              # encode the message, but pretty this time
              json_encode {
                  source =&gt; "body"
                  target =&gt; "body"
              }
          }
  
          # escape the body for HTML output
          mutate {
              add_field =&gt; { htmlbody =&gt; "%{body}" }
          }
          mutate {
              gsub =&gt; [
                  'htmlbody', '&amp;', '&amp;amp;',
                  'htmlbody', '&lt;', '&amp;lt;'
              ]
          }
      }
  }
  
  output {
      if "email" in [tags] and "throttled" not in [tags] {
          email {
              options =&gt; {
                  # config stuff...
              }
              body =&gt; "%{body}"
              htmlbody =&gt; "
  &lt;table&gt;
    &lt;tr&gt;&lt;td&gt;host:&lt;/td&gt;&lt;td&gt;%{host}&lt;/td&gt;&lt;/tr&gt;
    &lt;tr&gt;&lt;td&gt;when:&lt;/td&gt;&lt;td&gt;%{@timestamp}&lt;/td&gt;&lt;/tr&gt;
  &lt;/table&gt;
  &lt;pre&gt;%{htmlbody}&lt;/pre&gt;
  "
          }
      }
  }
  </code></pre>