SpringBoot的详细请求和响应日志记录

时间:2019-01-02 17:18:23

标签: spring-boot logging

Ruby on Rails为控制器中的“ Request”,“ Response”对象以及所用时间等提供了默认日志记录。在Spring Boot的情况下,有没有一种方法可以实现相同的功能而不必编写记录报表以打印请求,响应和花费的时间等。

PS:Python的Flask具有类似 Before After 的注释,但是我不确定我们如何完成Rich Rails,例如在Spring Boot中进行登录。

2 个答案:

答案 0 :(得分:1)

这样的事情怎么样?

@Configuration
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(new ControllerInterceptor()).addPathPatterns(ControllerInterceptor.PATTERN);
    }

public class ControllerInterceptor extends HandlerInterceptorAdapter {

    public static final String PATTERN = "/mycontrollermappingvalue*";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        System.out.println("Before request");
        //log values from HttpServletRequest
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
         System.out.println("After request");
        //log values from HttpServletResponse
    }
}

答案 1 :(得分:-1)

我认为您正在寻找Java面向方面的编程。看一下https://1drv.ms/u/s!AquuuuC3yZ55hkNbh3qHdRijQXGy示例。

以下是配置条目的示例,该条目最终记录了方法调用。

<aop:config> 
  <aop:aspect id="aspectService" ref="logAspect" > 
     <aop:pointcut id="pointCutBeforeBC"
    expression="execution(* com.test.application.service.*.*(..))" />
      <aop:before method="logBefore" pointcut-ref="pointCutBefore" /> 
  </aop:aspect> 

  <aop:aspect id="aspectUserInterface" ref="logAspect" > 
     <aop:pointcut id="pointCutBeforeUserInterfaceBA"
    expression="execution(* com.test.application.ui.*(..))" />
      <aop:before method="pointCutBeforeTraceInput" pointcut-ref="pointCutBeforeUserInterface" /> 
      <aop:after-throwing method="pointCutAfterThrowingOutput" throwing="_Throwable" pointcut-ref="pointCutBeforeUserInterface" />


  </aop:aspect> 
</aop:config>