簡體   English   中英

在使用@Requestbody注釋在Spring Boot中進行處理之前,如何在數據庫或日志文件中記錄JSON或XML請求

[英]How to log JSON or XML request in a database or log file before processing in Spring boot using @Requestbody annotation

在使用@RequestBody注釋在Spring Boot中進行處理之前,如何在數據庫或日志文件中記錄JSON或XML請求?

我可以使用哪個班級進行這項工作?

否則任何鏈接都會有所幫助。

您可以使用過濾器( CommonsRequestLoggingFilter類)方法,也可以將以下代碼與自定義實現一起使用

@Component
public class AppRequestInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(
      HttpServletRequest request, 
      HttpServletResponse response, 
      Object handler) {
        HttpServletRequest requestCacheWrapperObject = new ContentCachingRequestWrapper(request);
        //your implementation
        //sample method you can use: requestCacheWrapperObject.getParameterMap(); requestCacheWrapperObject.getContentAsByteArray();
        return true;
    }

    @Override
    public void afterCompletion(
      HttpServletRequest request, 
      HttpServletResponse response, 
      Object handler, 
      Exception ex) {
       //your implementation
    }
}


@Configuration
public class AppMVCConfig implements WebMvcConfigurer {

    @Autowired
    private AppRequestInterceptor appRequestInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(appRequestInterceptor)
          .addPathPatterns("/**");
    }
}

為了記錄請求有效負載,可以使用Spring提供的過濾器CommonsRequestLoggingFilter

將以下bean添加到您的Spring-Boot配置中,並將org.springframework.web.filter包的日志級別更改為DEBUG

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter rlFilter = new CommonsRequestLoggingFilter();
    rlFilter.setIncludePayload(true);
    return rlFilter;
}

此外,Spring Boot還提供了Actuator Endpoint(/ actuator / httptrace),用於開箱即用地進行HTTP請求登錄。 檢查下面的鏈接以獲取更多詳細信息:

彈簧啟動執行器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM