본문 바로가기

Java/Spring

에러 콘트롤러를 만들어 로그를 찍어보자

web.xml에 다음 코드를 추가하면 간단히 에러 페이지로 이동할 수 있다.

 <error-page>

  <error-code>404</error-code>

  <location>/error/error.html</location>

 </error-page>


 <error-page>

  <error-code>500</error-code>

  <location>/error/error.html</location>

 </error-page>


그런데 나는 error.html을 컨트롤러로 구현하여 로그를 찍어보고 싶었다. 에러코드, URI, 에러 메시지등.

가능해보여서 찾다가보니 쉽게 나오지 않는다. 일반적인 방식이 아닌모양이다. 순수 자바로 구현한 예제를 찾았다.

그렇게 해서 구현한 것이 다음과 같다.

Throwable throwable = (Throwable)req.getAttribute("javax.servlet.error.exception");

Integer statusCode = (Integer)req.getAttribute("javax.servlet.error.status_code");

String servletName = (String)req.getAttribute("javax.servlet.error.servlet_name");

if (servletName == null){

servletName = "Unknown";

}

String requestUri = (String)req.getAttribute("javax.servlet.error.request_uri");

if (requestUri == null){

requestUri = "Unknown";

}


LOG.info("!!!!!!!  ##### Error information #####");

LOG.info("!!!!!!!  The status code : " + statusCode);

LOG.info("!!!!!!!  Servlet Name : " + servletName);

LOG.info("!!!!!!!  The request URI: " + requestUri );

LOG.info("!!!!!!!  The exception message: " + throwable.getMessage());

LOG.info("!!!!!!!  Exception Type : " + throwable.getClass().getName() );


request를 이용해서 에러코드인 서버의 상태코드, 서블릿 이름, URI, 에러 메시지, 에러 타입등을 알 수 있다.

그런데 404 코드의 경우에는 throwable 이 오류나기 때문에 다음과 같이 해주면 된다.

LOG.info("!!!!!!!  ##### Error information #####");

LOG.info("!!!!!!!  The status code : " + statusCode);

LOG.info("!!!!!!!  Servlet Name : " + servletName);

LOG.info("!!!!!!!  The request URI: " + requestUri );

if(statusCode == 500){

LOG.info("!!!!!!!  The exception message: " + throwable.getMessage());

LOG.info("!!!!!!!  Exception Type : " + throwable.getClass().getName() );

}


이렇게 하면 문제없이 동작이 된다. 상태코드를 확인하다가 내가 모르는 내용이 더 있다는 것을 알았다. 5XX 상태코드는 서버 오류였다. 그래서 다음과 같이 수정해주면 좋을것 같다.

LOG.info("!!!!!!!  ##### Error information #####");

LOG.info("!!!!!!!  The status code : " + statusCode);

LOG.info("!!!!!!!  Servlet Name : " + servletName);

LOG.info("!!!!!!!  The request URI: " + requestUri );

if( (statusCode/100) == 5 ){

LOG.info("!!!!!!!  The exception message: " + throwable.getMessage());

LOG.info("!!!!!!!  Exception Type : " + throwable.getClass().getName() );

}


아직 다른 오류로 확인된건 없지만 동작은 잘 된다. 역시 훌륭한 사람은 넘처나는 구나. 훌륭해 지자.


참고 URL

http://www.tutorialspoint.com/servlets/servlets-exception-handling.htm

http://www.journaldev.com/1973/servlet-exception-and-error-handling-example-tutorial

http://ko.wikipedia.org/wiki/HTTP_%EC%83%81%ED%83%9C_%EC%BD%94%EB%93%9C


'Java > Spring' 카테고리의 다른 글

Spring4 웹 어플리케이션 생성하기  (0) 2018.01.23
logback library Exception 출력  (0) 2017.12.19
Spring + Maven 프로젝트 만들기  (0) 2014.03.03
dwr 오류  (0) 2012.08.01
스프링 버젼 확인하기  (0) 2012.06.28