복붙노트

[SPRING] Spring RestTemplate에서 응답을 어떻게 로그합니까?

SPRING

Spring RestTemplate에서 응답을 어떻게 로그합니까?

RestTemplate을 사용하여 웹 서비스를 호출합니다.

String userId = restTemplate.getForObject(createUserUrl, String.class);

이것이 사용자 ID를 반환하지 못하면 null이 반환되지만 이유는 알 수 없습니다. 실제 XML 응답을 로그에 어떻게 출력합니까?

해결법

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

    1.사용중인 HTTP 연결을 만드는 방법에 따라 실제 HTTP 연결 클래스 내에서 로깅을 시작할 수 있습니다.

    사용중인 HTTP 연결을 만드는 방법에 따라 실제 HTTP 연결 클래스 내에서 로깅을 시작할 수 있습니다.

    예를 들어, HttpClient 공유를 사용하는 경우,

    log4j.logger.httpclient.wire=DEBUG
    

    commons-httpclient 프로젝트는 문서의 로깅 관행에 대한 전체 페이지를 가지고 있습니다.

  2. ==============================

    2.다음과 같이 로깅을 구성하십시오.

    다음과 같이 로깅을 구성하십시오.

    log4j.logger.org.springframework.web.client=DEBUG
    

    그런 다음 curl 명령을 사용하여 출력을 봅니다.

    curl  -H 'Accept: application/xml' -H 'Content-Type: application/xml' http://localhost:8080/ser/data
    

    기본적으로 restTemplate은 (SimpleClientHttpRequest를 통해) HttpURlConnection을 사용하므로 로그 문을 보려면 jakarta httpclient로 전환해야 할 수도 있습니다. 그렇지 않으면 위의 로그 구성에서 응답을 표시합니다.

        <bean id="httpClientFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory">
            <constructor-arg><bean  class="org.apache.commons.httpclient.HttpClient"/></constructor-arg>
        </bean>
        <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
            <constructor-arg ref="httpClientFactory"/>
            <property name="messageConverters">
    ...
    
  3. ==============================

    3.spring-rest-template-logger를 사용하여 RestTemplate HTTP 트래픽을 기록 할 수 있습니다.

    spring-rest-template-logger를 사용하여 RestTemplate HTTP 트래픽을 기록 할 수 있습니다.

    Maven 프로젝트에 의존성 추가하기 :

    <dependency>
        <groupId>org.hobsoft.spring</groupId>
        <artifactId>spring-rest-template-logger</artifactId>
        <version>2.0.0</version>
    </dependency>
    

    그런 다음 RestTemplate을 다음과 같이 사용자 정의하십시오.

    RestTemplate restTemplate = new RestTemplateBuilder()
        .customizers(new LoggingCustomizer())
        .build()
    

    이제 모든 RestTemplate HTTP 트래픽은 디버그 레벨에서 org.hobsoft.spring.resttemplatelogger.LoggingCustomizer에 로깅됩니다.

    면책 조항 : 나는이 도서관을 썼다.

  4. from https://stackoverflow.com/questions/3892018/how-do-i-log-response-in-spring-resttemplate by cc-by-sa and MIT license