【问题标题】:Pretty print JSON output of Spring Boot Actuator endpointsSpring Boot Actuator 端点的漂亮打印 JSON 输出
【发布时间】:2014-08-21 15:08:57
【问题描述】:

Spring Boot Actuator 提供了几个端点监控一个应用程序

/metrics
/beans
/health
...

检查端点:

curl http://localhost:8080/metrics

结果:

{"counter.status.200.env":1,"counter.status.200.health":1,"counter.status.200.info":2,"counter.status.200.metrics":2,"gauge.response.env":5.0,"gauge.response.health":22.0,"gauge.response.info":1.0,"gauge.response.metrics":1.0,"mem":1030144,"mem.free":56118,"processors":8,"uptime":5108095,"instance.uptime":5102906,"heap.committed":1030144,"heap.init":262144,"heap.used":974031,"heap":3728384,"threads.peak":81,"threads.daemon":21,"threads":77,"classes":8854,"classes.loaded":8860,"classes.unloaded":6,"gc.ps_scavenge.count":119,"gc.ps_scavenge.time":7223,"gc.ps_marksweep.count":12,"gc.ps_marksweep.time":17573}

适合机器使用,但很难被人类阅读

我想格式化(即漂亮打印)Spring Boot Actuator 端点的 JSON 输出,使其更易于阅读由操作人员。

类似:

{
  "counter.status.200.env":1,
  "counter.status.200.health":1,
  "counter.status.200.info":2,
  "counter.status.200.metrics":2,
  "gauge.response.env":5.0,
  "gauge.response.health":22.0,
  "gauge.response.info":1.0,
  ...
}

我试过设置

http.mappers.json-pretty-print=true 

但此设置不影响执行器输出。

是否有配置启用漂亮打印 Spring Boot Actuator JSON输出?

更新:

official sample 适合我。

遵循@DaveSyer 的cmets 很重要:要设置的属性是

http.mappers.jsonPrettyPrint=true

调查仍在进行中。

与此同时,我使用 json 漂亮打印 命令行 作为解决方法

安装 jsonpp(例如用于 OS X):

brew install jsonpp

然后将 curl 输出通过 jsonpp 管道传输,它会即时格式化 json 文件:

curl http://localhost:8080/metrics | jsonpp

结果:

{
  "counter.status.200.env": 1,
  "counter.status.200.health": 1,
  "counter.status.200.info": 2,
  "counter.status.200.metrics": 2,
  ...
}

【问题讨论】:

标签: json spring spring-boot


【解决方案1】:

如果使用 Spring Boot 2(在我的情况下为 2.1.1)的人像我一样绊倒了这个问题:我们遇到了同样的问题,但没有一个答案对 2.1.1 有帮助。

所以我们所做的就是用一个新的端点替换现有的端点(在我们的例子中是health)。我在this answer的末尾描述了它。是的,这将我们的解决方案限制在这个单一端点,但另一方面,它具有能够以您想要的任何方式格式化输出的优势 - 包括漂亮的打印 JSON,但如果请求(通过服务)输出样式的 HTML在我们的案例中,浏览器中的技术人员)。请注意 @ReadOperationproduces 属性来实现这一点。

【讨论】:

    【解决方案2】:

    这不起作用

    spring.jackson.serialization.INDENT_OUTPUT=true

    这是有效的spring.jackson.serialization.indent-output=true

    【讨论】:

      【解决方案3】:

      如果您在 Spring 中使用 gson 序列化,那么其他答案都不适合您。您必须使用此配置选项:

      spring.gson.pretty-printing=true

      确认使用 Spring Boot 版本 2.0.3.Release

      【讨论】:

        【解决方案4】:

        我喜欢使用httpie而不是curl作为http命令行客户端:

        http http://localhost:8080/metrics

        这将已经格式化和语法突出显示 json 响应,而无需将输出传递到另一个命令。此外,命令语法更人性化。

        【讨论】:

          【解决方案5】:

          其实我也想这样做。但后来我问:为什么?为了更好地调试我的服务,这会带来很小的性能损失。

          只需使用浏览器扩展程序like this one :) 即可获得这样的视图

          【讨论】:

            【解决方案6】:

            对于 Spring Boot 1.5.1,我的 YML 文件中有:

            spring:
              jackson:
                serialization:
                  INDENT_OUTPUT: true
            

            @BertrandRenuart 的答案是最接近的,但 IDE 认为 indent_output 不正确。

            【讨论】:

              【解决方案7】:

              我使用jq 来漂亮地打印 JSON 并对其进行过滤。对于 JSON,它基本上是 sed。在 mac 上,可以使用 homebrew 安装。 (https://stedolan.github.io/jq/)

              curl http://localhost:8080/metrics | jq 
              

              【讨论】:

                【解决方案8】:

                这是我的 Emacs 函数,用于从端点检索 Spring Actuator Json:

                (defvar my/spring-actuator-server-history nil)
                (defvar my/spring-actuator-last-server "http://localhost:8080")
                (defvar my/spring-actuator-path-history nil)
                (defvar my/spring-actuator-path-completion
                  '("actuator" "auditevents" "autoconfig" "beans" "configprops" "dump" "env" "flyway" "health" "heapdump"
                    "info" "jolokia" "liquibase" "logfile" "loggers" "mappings" "metrics" "shutdown" "trace")))
                
                (defun my/spring-actuator (server path)
                  (interactive (list (read-string "Server: " my/spring-actuator-last-server 'my/spring-actuator-server-history)
                                     (completing-read "Path: " my/spring-actuator-path-completion nil nil "" 'my/spring-actuator-path-history)))
                  (setq my/spring-actuator-last-server server)
                  (let ( (bufname (format "actuator: %s" path)) )
                    (when (get-buffer bufname)
                      (kill-buffer bufname))
                    (switch-to-buffer (url-retrieve-synchronously (format "%s/%s" server path)))
                    (rename-buffer bufname)
                    (goto-char (point-min))
                    (re-search-forward "^$" nil 'move)
                    (forward-char)
                    (delete-region (point-min) (point))
                    (json-pretty-print-buffer)
                    (json-mode) ))
                

                如果您不喜欢依赖外部 json-mode 库,请将其替换为 js-mode

                【讨论】:

                  【解决方案9】:

                  不幸的是,应用程序属性

                  spring.jackson.serialization.INDENT_OUTPUT

                  对我不起作用(弹簧启动版本 1.2.6 到 1.4.0.RELEASE)。相反,在我的 WebMvcConfigurerAdapter 扩展中,我重写了 configureMessageConverters() 并添加了我自己的 Jackson2ObjectMapperBuilder:

                  @Configuration
                  @EnableWebMvc
                  public class WebMvcConfig extends WebMvcConfigurerAdapter {
                     ...
                      private MappingJackson2HttpMessageConverter jacksonMessageConverter() {
                          Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
                                  .featuresToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS,
                                          SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS)
                                  .featuresToEnable(SerializationFeature.INDENT_OUTPUT).modulesToInstall(hibernate4Module());
                          // can use this instead of featuresToEnable(...)
                          builder.indentOutput(true);
                          return new MappingJackson2HttpMessageConverter(builder.build());
                      }
                  
                  
                      @Override
                      public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
                          converters.add(jacksonMessageConverter());
                          super.configureMessageConverters(converters);
                      }
                  
                     ...
                  
                  }
                  

                  这似乎在 Spring boot 1.4.0.RELEASE 上对我有用,而且我的执行器输出现在打印得很漂亮(以及所有其他 json 输出)

                  【讨论】:

                    【解决方案10】:

                    使用spring-boot 1.2.6,需要使用:

                    spring.jackson.serialization.INDENT_OUTPUT=true
                    

                    使用旧的 http.mappers.* 时来自我的日志:

                    http.mappers.json-pretty-print is deprecated. If you are using Jackson, spring.jackson.serialization.INDENT_OUTPUT=true should be used instead.
                    

                    【讨论】:

                      【解决方案11】:

                      根据http://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper,在 Spring Boot(至少 1.2.2)中启用 Jackson 漂亮打印的官方方法是设置以下属性:

                       # Pretty-print JSON responses
                       spring.jackson.serialization.indent_output=true
                      

                      【讨论】:

                      • 它对我有用,altought STS 给出了这个错误:“期望 com.fasterxml.jackson.databind.SerializationFeature[WRAP_ROOT_VALUE, INDENT_OUTPUT, FAIL_ON_EMPTY_BEANS, FAIL_ON_SELF_REFERENCES, ...]”
                      • 漂亮的打印机是根据 3 次检查(a && b && c)打开的,只有这一个可以通过配置打开false...有点难找。
                      【解决方案12】:

                      我使用Python常用的安装json.tool模块:

                      curl --silent http://localhost:8080/metrics | python -mjson.tool
                      

                      【讨论】:

                      • 我还发现它是最好的选择。 jqpython -m simplejson.tool 可以用作替代漂亮的打印机。在控制台中使用pygmentize -l json 处理可能很有用。所有工具都在 Cygwin/Brew/Deb/RPM 中可用。
                      【解决方案13】:

                      执行以下操作:

                      @Configuration
                      public class JacksonConfig {
                      
                          @Autowired
                          private ObjectMapper objectMapper; //reuse the pre-configured mapper
                      
                      
                          @PostConstruct
                          public void setup() {
                              objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
                              //whatever else you need
                          }
                      
                      
                      }
                      

                      这是因为 Spring Boot 使用 ObjectMapper bean 来执行所有与 JSON 相关的操作。

                      但是请注意,此配置将漂亮地打印所有 JSON 输出,而不仅仅是与执行器相关的内容。

                      更新

                      @DaveSyer 的答案显然更好!我没有找到用于配置 Jackson 的 HttpMapperProperties 对象。 This 是 Javadoc

                      【讨论】:

                        【解决方案14】:

                        “http.mappers”属性对我有用,但我认为您可能需要它的驼峰式(“jsonPrettyPrint”)。

                        【讨论】:

                        • 谢谢!更改为http.mappers.jsonPrettyPrint=true 后,HttpMapperProperties 中的设置器被调用,但输出不受影响(docs.spring.io/spring-boot/docs/1.1.3.RELEASE/reference/… 中可能存在文档问题,它指出http.mappers.json-pretty-print)。我可能仍然缺少一些其他配置...
                        • 就像我说的,它对我有用。如果未应用该设置,我怀疑您的应用中可能有其他东西将其关闭(例如自定义 ObjectMapper)。
                        • 跟踪应用程序初始化表明创建了 7 个 MappingJackson2HttpMessageConverter 实例,其中只有一个配置了 prettyPrint()
                        • 如果那样的话,您可能必须共享一些代码才能查明真相。 (就像我说的,它适合我。)
                        • 谢谢,在下面添加 yaml 配置工作
                          http.mappers: jsonPrettyPrint: true
                        猜你喜欢
                        • 2015-10-23
                        • 2016-07-07
                        • 1970-01-01
                        • 1970-01-01
                        • 2014-05-19
                        • 1970-01-01
                        • 1970-01-01
                        • 2021-01-31
                        • 2014-05-12
                        相关资源
                        最近更新 更多