membersound
membersound

Reputation: 86627

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?

Upvotes: 7

Views: 8691

Answers (2)

Fritz Duchardt
Fritz Duchardt

Reputation: 11860

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
}

Upvotes: 1

Marcelo Keiti
Marcelo Keiti

Reputation: 1240

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>

Upvotes: 2

Related Questions