7

How can I automatically log any incoming GET url requests on a REST service written with Spring?

@RestController
public class MyRest {
    @RequestMapping(method = RequestMethod.GET,
            produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public ComplexRsp test() {
        //...
    }
}

I have used cxf for soap, where logging is as easy as annotation the webservice with @InInterceptors, @OutInterceptors.

Is there anything similar in spring for rest?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

2 Answers2

2

You can just enable log4j org.springframework.security if you are using spring security, but it's very verbose:

<category name="org.springframework.security">
   <priority value="ALL" />
</category>

Or you can implement an interceptor:

public class LoggerInterceptor extends HandlerInterceptorAdapter {    
    private static final Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("pre hangle URI: " + request.getRequestURI());

        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        logger.info("post hangle URI: " + request.getRequestURI());

        super.afterCompletion(request, response, handler, ex);
    }    
}

applicationContext.xml

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**" />
        <bean class="com.mycompany.LoggerInterceptor"></bean>
    </mvc:interceptor>
</mvc:interceptors>
Marcelo Keiti
  • 1,200
  • 9
  • 10
  • verbose logging not useful for me, but the interceptor looks promising. How can I add him when using spring4 annotation based configuration only, without any xml? – membersound Feb 20 '15 at 17:07
  • try this: http://stackoverflow.com/questions/4389224/is-it-possible-to-wire-a-spring-mvc-interceptor-using-annotations – Marcelo Keiti Feb 20 '15 at 17:14
1

This might be a bit of a hack, but for sure it is easy. Simply add a @ModelAttribute annotated method to your controller. Spring will invoke it every time before it calls any handler method. Response and request object can be added to the signature, Spring will inject them:

@ModelAttribute
protected void logging(HttpServletRequest request, HttpServletResponse response) { 
  // do your logging here
}
Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60