json - 如何在 logstash 中漂亮地打印电子邮件正文的 JSON?

标签 json logstash logstash-configuration

我有一个 Logstash 配置,我一直使用它来转发电子邮件中的日志消息。它使用 jsonjson_encode 来解析和重新编码 JSON 日志消息。

json_encode 用于漂亮地打印 JSON,这使得电子邮件看起来非常漂亮。不幸的是,随着最近的 Logstash 升级,它不再 pretty-print 。

有什么方法可以将事件的漂亮形式放入可用于电子邮件正文的字段中?我擅长 JSON、Ruby 调试或大多数其他人类可读的格式。

filter {
    if [type] == "bunyan" {
        # Save a copy of the message, in case we need to pretty-print later
        mutate {
            add_field => { "@orig_message" => "%{message}" }
        }

        json {
            source => "message"
            add_tag => "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 => "@orig_message"
                target => "body"
            }

            # encode the message, but pretty this time
            json_encode {
                source => "body"
                target => "body"
            }
        }

        # escape the body for HTML output
        mutate {
            add_field => { htmlbody => "%{body}" }
        }
        mutate {
            gsub => [
                'htmlbody', '&', '&',
                'htmlbody', '<', '&lt;'
            ]
        }
    }
}

output {
    if "email" in [tags] and "throttled" not in [tags] {
        email {
            options => {
                # config stuff...
            }
            body => "%{body}"
            htmlbody => "
<table>
  <tr><td>host:</td><td>%{host}</td></tr>
  <tr><td>when:</td><td>%{@timestamp}</td></tr>
</table>
<pre>%{htmlbody}</pre>
"
        }
    }
}

最佳答案

正如 approxiblue 所说,这个问题是由 logstash 的 new JSON parser 引起的(小 jackson )。您可以使用 old parser作为解决方法,直到再次添加 pretty-print 支持。方法如下:

您需要更改插件的 ruby​​ 文件的两行。路径应该是这样的:

LS_HOME/vendor/bundle/jruby/1.9/gems/logstash-filter-json_encode-0.1.5/lib/logstash/filters/json_encode.rb

改变行 5

require "logstash/json" 

进入

require "json" 

并更改行44

event[@target] = LogStash::Json.dump(event[@source])

进入

event[@target] = JSON.pretty_generate(event[@source])

就是这样。重新启动 logstash 后应该再次 pretty-print 。

补充:

如果您不喜欢更改 ruby​​ 源,您也可以使用 ruby​​ 过滤器而不是 json_encode:

# encode the message, but pretty this time
ruby  {
    init => "require 'json'"
    code => "event['body'] = JSON.pretty_generate(event['body'])"
}

关于json - 如何在 logstash 中漂亮地打印电子邮件正文的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32077228/

相关文章:

objective-c - 获取正确的 Node Json objective c

json - Spring 4.1.1 RELEASE 和 @ResponseBody 返回 HTTP 406

java - 如何将包含 LocalDate 字段的 json 转换为可反序列化格式?

json - 如何获得MVC Action 以返回错误状态

elasticsearch - 将坐标存储为geo_point的问题

azure - Logstash azure 插件

elasticsearch - 使用摄取附件批量索引(约40k个.docx类型文件)的嵌套方式是什么?

Logstash add_field和replace的区别

elasticsearch - 如何减少 Logstash 的 RAM 使用量?

jdbc - logstash jdbc 上的多个输入