Spring Cloud Gateway 记录请求应答数据日志操作

论坛 期权论坛     
niminba   2021-5-22 15:04   1061   0
<p>我就废话不多说了,大家还是直接看代码吧~</p>
<div class="blockcode">
<pre class="brush:java;">
public class GatewayContext {
public static final String CACHE_GATEWAY_CONTEXT = "cacheGatewayContext";
/**
  * cache json body
  */
private String cacheBody;
/**
  * cache formdata
  */
private MultiValueMap&lt;String, String&gt; formData;
/**
  * cache reqeust path
  */
private String path;
public String getCacheBody() {
  return cacheBody;
}
public void setCacheBody(String cacheBody) {
  this.cacheBody = cacheBody;
}
public MultiValueMap&lt;String, String&gt; getFormData() {
  return formData;
}
public void setFormData(MultiValueMap&lt;String, String&gt; formData) {
  this.formData = formData;
}
public String getPath() {
  return path;
}
public void setPath(String path) {
  this.path = path;
}
}
</pre>
</div>
<div class="blockcode">
<pre class="brush:java;">
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import io.netty.buffer.ByteBufAllocator;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
// https://segmentfault.com/a/1190000017898354
@Component
public class LogRequestGlobalFilter
  implements GlobalFilter {
/**
  * default HttpMessageReader
  */
private static final List&lt;HttpMessageReader&lt;&#63;&gt;&gt; messageReaders =
   HandlerStrategies.withDefaults().messageReaders();
private Logger log = LoggerFactory.getLogger(LogRequestGlobalFilter.class);
@Override
public Mono&lt;Void&gt; filter(
   ServerWebExchange exchange,
   GatewayFilterChain chain) {
  /**
   * save request path and serviceId into gateway context
   */
  ServerHttpRequest request = exchange.getRequest();
  String path = request.getPath().pathWithinApplication().value();
  GatewayContext gatewayContext = new GatewayContext();
  gatewayContext.setPath(path);
  /**
   * save gateway context into exchange
   */
  exchange.getAttributes().put(GatewayContext.CACHE_GATEWAY_CONTEXT,
    gatewayContext);
  HttpHeaders headers = request.getHeaders();
  MediaType contentType = headers.getContentType();
  log.info("start-------------------------------------------------");
  log.info("HttpMethod:{},Url:{}", request.getMethod(),
    request.getURI().getRawPath());
  log.info("Headers token: {}", headers.getFirst("token"));
  if (request.getMethod() == HttpMethod.GET) {
   log.info("end-------------------------------------------------");
  }
  if (request.getMethod() == HttpMethod.POST) {
   Mono&lt;Void&gt; voidMono = null;
   if (MediaType.APPLICATION_JSON.equals(contentType)
     || MediaType.APPLICATION_JSON_UTF8.equals(contentType)) {
    voidMono =
      readBody(exchange, chain, gatewayContext);
   }
   if (MediaType.APPLICATION_FORM_URLENCODED.equals(contentType)) {
    voidMono =
      readFormData(exchange, chain, gatewayContext);
   }
   return voidMono;
  }
  /* log.debug(
   "[GatewayContext]ContentType:{},Gateway context is set with {}",
   contentType, gatewayContext);*/
  return chain.filter(exchange);
}
/**
  * ReadFormData
  *
  * @param exchange
  * @param chain
  * @return
  */
private Mono&lt;Void&gt; readFormData(
   ServerWebExchange exchange,
   GatewayFilterChain chain,
   GatewayContext gatewayContext) {
  final ServerHttpRequest request = exchange.getRequest();
  HttpHeaders headers = request.getHeaders();
  return exchange.getFormData()
    .doOnNext(multiValueMap -&gt; {
     gatewayContext.setFormData(multiValueMap);
     log.info("Post x-www-form-urlencoded:{}",
       multiValueMap);
     log.info(
       "end-------------------------------------------------");
    })
    .then(Mono.defer(() -&gt; {
     Charset charset = headers.getContentType().getCharset();
     charset = charset == null &#63; StandardCharsets.UTF_8 : charset;
     String charsetName = charset.name();
     MultiValueMap&lt;String, String&gt; formData =
       gatewayContext.getFormData();
     /**
      * formData is empty just return
      */
     if (null == formData || formData.isEmpty()) {
      return chain.filter(exchange);
     }
     StringBuilder formDataBodyBuilder = new StringBuilder();
     String entryKey;
     List&lt;String&gt; entryValue;
     try {
      /**
       * repackage form data
       */
      for (Map.Entry&lt
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1060120
帖子:212021
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP