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

7

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

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

我之前用过 cxf 来处理 soap 相关内容,其中使用注解 @InInterceptors, @OutInterceptors 就可以轻松实现日志记录。

那么在 Spring 中是否有类似的功能来处理 rest 呢?

2个回答

2
如果您正在使用Spring Security,可以启用log4j org.springframework.security,但它非常冗长。
<category name="org.springframework.security">
   <priority value="ALL" />
</category>

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

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>

冗长的日志记录对我没有用,但拦截器看起来很有前途。在仅使用基于Spring4注释的配置且没有任何XML的情况下,我该如何添加它? - membersound
尝试这个: https://dev59.com/cW855IYBdhLWcg3wXS8I - Marcelo Keiti

1

这可能有点取巧,但肯定是容易的。只需在控制器中添加一个带有@ModelAttribute注释的方法即可。Spring将在调用任何处理程序方法之前每次调用它。响应和请求对象可以添加到签名中,Spring将自动注入它们:

@ModelAttribute
protected void logging(HttpServletRequest request, HttpServletResponse response) { 
  // do your logging here
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接