Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable logging for @RestController?

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?

like image 919
membersound Avatar asked Feb 20 '15 16:02

membersound


2 Answers

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>
like image 197
Marcelo Keiti Avatar answered Oct 22 '22 06:10

Marcelo Keiti


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
}
like image 35
Fritz Duchardt Avatar answered Oct 22 '22 07:10

Fritz Duchardt