복붙노트

[SPRING] 스프링 부트 액추에이터 엔드 포인트의 JSON 출력을 멋지게 출력

SPRING

스프링 부트 액추에이터 엔드 포인트의 JSON 출력을 멋지게 출력

스프링 부트 액추에이터는 다음과 같이 애플리케이션을 모니터링하기위한 여러 엔드 포인트를 제공합니다.

/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}

이것은 기계 소비에는 좋지만 인간에 의해 읽기는 어렵습니다.

스프링 원스 액추에이터 엔드 포인트의 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 출력을 출력하기위한 설정이 있습니까?

최신 정보:

공식 견본은 나를 위해 일한다.

@DaveSyer의 의견을 따르는 것이 중요합니다. 설정할 속성은 다음과 같습니다.

http.mappers.jsonPrettyPrint=true

조사가 아직 진행 중이다.

그 동안 json pretty print 명령 줄을 임시 해결책으로 사용합니다.

jsonpp 설치 (예 : OS X) :

brew install 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,
  ...
}

해결법

  1. ==============================

    1.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은 다음 속성을 설정하는 것입니다.

    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
    
  2. ==============================

    2.스프링 부트 1.5.1의 경우 YML 파일에 있습니다.

    스프링 부트 1.5.1의 경우 YML 파일에 있습니다.

    spring:
      jackson:
        serialization:
          INDENT_OUTPUT: true
    

    @ BertrandRenuart 대답은 가장 가까웠지만 IDE는 indent_output을 올바른 것으로 보지 않았습니다.

  3. ==============================

    3."http.mappers"속성은 저에게 효과적이지만 낙타가 필요하다고 생각합니다 ( "jsonPrettyPrint").

    "http.mappers"속성은 저에게 효과적이지만 낙타가 필요하다고 생각합니다 ( "jsonPrettyPrint").

  4. ==============================

    4.다음을 수행하십시오.

    다음을 수행하십시오.

    @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
        }
    
    
    }
    

    이것은 스프링 부트가 ObjectMapper 빈을 사용하여 모든 JSON 관련 연산을 수행하기 때문에 가능합니다.

    그러나이 구성은 액추에이터 관련 항목뿐만 아니라 모든 JSON 출력을 출력합니다.

    최신 정보

    @DaveSyer의 대답은 분명히 좋습니다! Jackson을 구성하는 데 사용되는 HttpMapperProperties 객체를 찾지 못했습니다. 이것은 Javadoc입니다.

  5. ==============================

    5.사실 나는 같은 것을하고 싶었다. 그러나 그 때 나는 물었다 : 왜? 작은 성능 저하가 따르는 내 서비스를 디버깅하려면.

    사실 나는 같은 것을하고 싶었다. 그러나 그 때 나는 물었다 : 왜? 작은 성능 저하가 따르는 내 서비스를 디버깅하려면.

    다음과 같은보기를 얻으려면 다음과 같은 브라우저 확장 프로그램을 사용하십시오.

  6. ==============================

    6.파이썬의 일반적으로 설치된 json.tool 모듈을 사용합니다.

    파이썬의 일반적으로 설치된 json.tool 모듈을 사용합니다.

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

    7.spring-boot 1.2.6에서는 다음을 사용해야합니다.

    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.
    
  8. ==============================

    8.곱슬 곱슬 함을 사용하는 대신 HTTP 커맨드 라인 클라이언트로 httpie를 사용하고 싶습니다 :

    곱슬 곱슬 함을 사용하는 대신 HTTP 커맨드 라인 클라이언트로 httpie를 사용하고 싶습니다 :

    http http : // localhost : 8080 / metrics

    이것은 이미 출력을 다른 명령으로 파이프하지 않고도 json 응답을 형식화하고 구문을 강조합니다. 또한 명령 구문은 좀 더 인간 친화적입니다.

  9. ==============================

    9.Spring과 함께 gson serialization을 사용한다면, 다른 답변들도 당신을 위해 작동하지 않을 것입니다. 이 구성 옵션을 사용해야합니다.

    Spring과 함께 gson serialization을 사용한다면, 다른 답변들도 당신을 위해 작동하지 않을 것입니다. 이 구성 옵션을 사용해야합니다.

    spring.gson.pretty-printing = true

    스프링 부트 2.0.3 버전으로 작동 확인. 릴리스.

  10. ==============================

    10.불행히도 응용 프로그램 속성

    불행히도 응용 프로그램 속성

    나를 위해 (봄 부팅 버전 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);
        }
    
       ...
    
    }
    

    그건 스프링 부팅 1.4.0.RELEASE와 내 액추에이터 출력에 대한 트릭을 이제 꽤 인쇄됩니다 (다른 모든 json 출력과 함께)

  11. ==============================

    11.다음은 Emacs에서 Endpoint에서 Spring Actuator Json을 검색하는 함수입니다.

    다음은 Emacs에서 Endpoint에서 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로 바꿉니다.

  12. ==============================

    12.JSON을 꽤 잘 인쇄하고 필터링하는 데 jq를 사용합니다. 그것은 기본적으로 JSON에 대한 sed이야. Mac에서는 자작과 함께 설치할 수 있습니다. (https://stedolan.github.io/jq/)

    JSON을 꽤 잘 인쇄하고 필터링하는 데 jq를 사용합니다. 그것은 기본적으로 JSON에 대한 sed이야. Mac에서는 자작과 함께 설치할 수 있습니다. (https://stedolan.github.io/jq/)

    curl http://localhost:8080/metrics | jq 
    
  13. ==============================

    13.누군가 내게 스프링 부트 2 (2.1.1)이이 질문에 걸려 넘어지면 같은 문제에 직면하게되고 2.1.1에 도움이되는 대답은 하나도 없습니다.

    누군가 내게 스프링 부트 2 (2.1.1)이이 질문에 걸려 넘어지면 같은 문제에 직면하게되고 2.1.1에 도움이되는 대답은 하나도 없습니다.

    그래서 우리가 한 것은 기존 엔드 포인트 (우리의 경우 건강)를 새로운 엔드 포인트로 대체하는 것입니다. 나는이 대답의 끝에 그것을 기술했다. 그리고 그렇습니다.이 솔루션은이 단일 엔드 포인트에 대한 솔루션을 제한하지만 다른 한편으로는 원하는 방식으로 출력 형식을 지정할 수 있다는 장점이 있습니다. 예를 들어, JSON 인쇄를 비롯하여 요청 된 경우 출력 스타일이 지정된 HTML (서비스 우리의 경우 브라우저의 기술자). 그것을 달성하기 위해 @ReadOperation의 produce 속성에 주목하십시오.

  14. ==============================

    14.이건 작동하지 않아.

    이건 작동하지 않아.

    spring.jackson.serialization.INDENT_OUTPUT = true

    이것은 작동 중입니다. spring.jackson.serialization.indent-output = true

  15. from https://stackoverflow.com/questions/24503790/pretty-print-json-output-of-spring-boot-actuator-endpoints by cc-by-sa and MIT license