如何为@RestController 启用日志记录?

mem*_*und 6 java rest spring web-services

如何GET在用REST编写的服务上自动记录任何传入的url 请求Spring

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

我已经使用了cxffor soap,其中日志记录就像使用@InInterceptors, @OutInterceptors.

春天有什么类似的休息吗?

Mar*_*iti 2

如果您使用的是 spring security,则可以启用 log4j org.springframework.security,但它非常冗长:

<category name="org.springframework.security">
   <priority value="ALL" />
</category>
Run Code Online (Sandbox Code Playgroud)

或者你可以实现一个拦截器:

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);
    }    
}
Run Code Online (Sandbox Code Playgroud)

应用程序上下文.xml

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**" />
        <bean class="com.mycompany.LoggerInterceptor"></bean>
    </mvc:interceptor>
</mvc:interceptors>
Run Code Online (Sandbox Code Playgroud)