홍이의 개발 노트

스프링에서 웹 또는 API 개발시 요청정보 로깅 방법 본문

개발이야기/스프링(Spring)

스프링에서 웹 또는 API 개발시 요청정보 로깅 방법

코바 2017. 5. 6. 18:04

스프링 MVC로 웹을 개발 할 때 요청정보 즉 HTTP 정보 전체를 로깅 하고 싶을 때가 있다.


특히 개발시에서 제대로 요청을 하고 있는지 많이 궁금할 것이다. 


보통 웹서버에서 남겨주는 엑세스로그 같은 경우에는 요청된 url 과 응답 코드 등 기본정보만 제공 하는데 많이 부족 할 때가 있다.


예를 들면 body정보가 남지 않기 때문에 개발시에 많이 부족 하게 된다.


그래서 스프링MVC 에서 예전부터 지원하는 필터가 존재하는데 의외로 모르는 분이 많이 있어서 이렇게 다시 소개 한다.


@Bean
public CommonsRequestLoggingFilter commonsRequestLoggingFilter() {
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
filter.setIncludeClientInfo(true);
filter.setIncludeHeaders(true);
filter.setIncludePayload(true);
filter.setIncludeQueryString(true);
filter.setMaxPayloadLength(1000);
return filter;
}

스프링 부트 또는 일반 스프링 MVC 프로젝트에서도 사용 가능하며 


위와 같이 설정만 해주면 된다.


대략 로깅 결과는 아래 처럼 나온다.


2017-05-06 18:15:25.049 DEBUG 11917 --- [nio-8080-exec-7] o.s.w.f.CommonsRequestLoggingFilter      : Before request [uri=/test?a-a=1;client=0:0:0:0:0:0:0:1;session= 2111CBED0085376938B9A499DE94206CB13;headers={host=[localhost:8080], connection=[keep-alive], content-length=[0], origin=[http://localhost:8080], user-agent=[Mozilla/5.0 (Macintosh; Intel Mac OS X 9_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36], content-type=[text/plain; charset=utf-8], accept=[*/*], referer=[http://localhost:8080/], accept-encoding=[gzip, deflate, br], accept-language=[ko,en-US;q=0.8,en;q=0.6], cookie=[JSESSIONID= 2111CBED0085376938B9A499DE94206CB13]}]


2017-05-06 18:15:25.050 DEBUG 11917 --- [nio-8080-exec-7] o.s.w.f.CommonsRequestLoggingFilter      : After request [uri=/test?a=1;client=0:0:0:0:0:0:0:1;session= 2111CBED0085376938B9A499DE94206CB13;headers={host=[localhost:8080], connection=[keep-alive], content-length=[0], origin=[http://localhost:8080], user-agent=[Mozilla/5.0 (Macintosh; Intel Mac OS X 9_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36], content-type=[text/plain; charset=utf-8], accept=[*/*], referer=[http://localhost:8080/], accept-encoding=[gzip, deflate, br], accept-language=[ko,en-US;q=0.8,en;q=0.6], cookie=[JSESSIONID=2111CBED0085376938B9A499DE94206CB13]};payload=a=1&b=2&c=3&name=xx]]


만약에 web.xml 을 사용하게 되면 아래와 같이 설정 하면된다.

<filter>
<filter-name>requestLoggingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CommonsRequestLoggingFilter
</filter-class>
<init-param>
<param-name>includePayload</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>includeHeaders</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>includeClientInfo</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>includeQueryString</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>requestLoggingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

쉬운 설정으로 바로 사용할 수 있기 때문에 수고에 비해서 쓸만하다.