【问题标题】:Detailed Request and response logging for SpringBootSpring Boot 的详细请求和响应日志记录
【发布时间】:2019-01-02 17:18:22
【问题描述】:

Ruby on Rails 为控制器中的“请求”、“响应”对象以及花费的时间等提供默认日志记录。有没有一种方法可以在 Spring Boot 的情况下完成相同的操作,而无需编写记录语句以打印请求、响应和所用时间等。

PS : Python 的 Flask 有类似 Before 和 After 的注解,但我不知道我们如何才能像登录 Spring Boot 那样完成 Rich Rails。

【问题讨论】:

  • 我担心没有,但是您可以使用 AOP 面向方面的编程在您考虑的方法上进行一般的前后记录。

标签: spring-boot logging


【解决方案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
    }
}

【讨论】:

    【解决方案2】:

    我认为您正在寻找 Java 面向方面的编程。看看this 的例子。

    这是一个最终记录方法调用的配置条目示例。

    <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>
    

    【讨论】:

      猜你喜欢
      • 2012-10-08
      • 2015-09-10
      • 2014-06-13
      • 2020-08-18
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 2017-08-07
      相关资源
      最近更新 更多