简体   繁体   English

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

[英]How to enable logging for @RestController?

How can I automatically log any incoming GET url requests on a REST service written with Spring ? 如何在使用Spring编写的REST服务上自动记录任何传入的GET URL请求?

@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 . 我使用cxf for soap ,其中日志记录就像使用@InInterceptors, @OutInterceptors注释Web服务一样简单。

Is there anything similar in spring for rest? 春天有什么类似的休息吗?

You can just enable log4j org.springframework.security if you are using spring security, but it's very verbose: 如果您使用的是spring安全性,则可以启用log4j org.springframework.security,但它非常详细:

<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 applicationContext.xml中

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**" />
        <bean class="com.mycompany.LoggerInterceptor"></bean>
    </mvc:interceptor>
</mvc:interceptors>

This might be a bit of a hack, but for sure it is easy. 这可能是一个黑客攻击,但肯定很容易。 Simply add a @ModelAttribute annotated method to your controller. 只需将@ModelAttribute注释方法添加到控制器即可。 Spring will invoke it every time before it calls any handler method. Spring每次调用任何处理程序方法之前都会调用它。 Response and request object can be added to the signature, Spring will inject them: 响应和请求对象可以添加到签名中,Spring会注入它们:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM