Spring Cloud Gateway loggin request and response on firehose with header and body

Viewed 68

I need some help using Spring Cloud Gateway.

I am filtering a Request (Post and Get) redirecting because I need to log the request and response on AWS firehose.

My logging must have for the Request the Method Value, Uri address, Header and Body (as a json). And for response must have Status Code, Header and Body.

My problem is, how do I get the body of the request and response from ServerWebExchange? I tried many things, but none of them worked.

My code:

@Component
class GatewayGlobalFilter(var logging : LoggingUseCase): GlobalFilter, Ordered {

    override fun filter(exchange: ServerWebExchange,
                        chain: GatewayFilterChain): Mono<Void> {

        val uuid = UUID.randomUUID()

        return chain.filter(exchange).doFirst {
            Mono.just(logRequest(exchange, uuid)).subscribe(
                    logging::sendRequest,
                    Throwable::printStackTrace
            )
        }.then(
            Mono.fromRunnable{
                logging.sendResponse(logResponse(exchange, uuid))
            }
        )
    }

    private fun logRequest(exchange: ServerWebExchange, uuid: UUID): MyRequest {

        val jsonHeader = gson.toJson(exchange.request.headers)
        val jsonBody = ???
        val request = MyRequest(
                exchange.request.methodValue,
                exchange.request.uri.toString(),
                jsonHeader,
                jsonBody,
                uuid.toString()
        )
        return request
    }

    private fun logResponse(exchange: ServerWebExchange, uuid: UUID): MyResponse {

        val jsonHeader = gson.toJson(exchange.response.headers)
        val jsonBody = ???
        val response = MyResponse(
                exchange.response.rawStatusCode!!,
                jsonHeader,
                jsonBody,
                uuid.toString()
        )
        return response
    }

    override fun getOrder(): Int = -1
}
0 Answers
Related