相关疑难解决方法(0)

如何在Spring WebFlux中记录请求和响应主体

我希望使用Kotlin在Spring WebFlux上的REST API中集中记录请求和响应.到目前为止,我已经尝试过这种方法

@Bean
fun apiRouter() = router {
    (accept(MediaType.APPLICATION_JSON) and "/api").nest {
        "/user".nest {
            GET("/", userHandler::listUsers)
            POST("/{userId}", userHandler::updateUser)
        }
    }
}.filter { request, next ->
    logger.info { "Processing request $request with body ${request.bodyToMono<String>()}" }
    next.handle(request).doOnSuccess { logger.info { "Handling with response $it" } }
}
Run Code Online (Sandbox Code Playgroud)

这里请求方法和路径日志成功但身体是Mono,所以我该如何记录呢?应该是相反的方式,我必须订阅请求正文Mono并将其记录在回调中?另一个问题是ServerResponse这里的接口无法访问响应主体.我怎么能在这里得到它?


我尝试过的另一种方法是使用 WebFilter

@Bean
fun loggingFilter(): WebFilter =
        WebFilter { exchange, chain ->
            val request = exchange.request
            logger.info { "Processing request method=${request.method} path=${request.path.pathWithinApplication()} params=[${request.queryParams}] body=[${request.body}]"  }

            val result …
Run Code Online (Sandbox Code Playgroud)

kotlin spring-boot project-reactor spring-webflux

21
推荐指数
5
解决办法
2万
查看次数