基于Spring-cloud-gateway实现全局日志记录

这篇具有很好参考价值的文章主要介绍了基于Spring-cloud-gateway实现全局日志记录。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一 引言

最近项目在线上运行出现了一些难以复现的bug需要定位相应api的日志,通过nginx提供的api请求日志难以实现,于是在gateway通过全局过滤器记录api请求日志。

二 实现逻辑

基于Spring-cloud-gateway实现全局日志记录

  1. 接受到用户请求后,经过全局过滤器,检验是否开启相应的日志配置及相应的黑白名单配置
  2. 在gateway前置处理如记录当前请求开始时间,请求url,请求方法等
  3. 在gateway后置处理中获得相应的请求结果,响应状态码
  4. 记录当前请求日志,根据实际需求,通过mq异步处理工具持久化相应的日志(本案列作处理)
  5. 诊断请求结果,对请求异常,慢api等推送相应的消息给研发人人员

三 代码实现

定义相应的配置类

@Data
@RefreshScope
@Component
@ConfigurationProperties(prefix = LogProperties.PREFIX)
public class LogProperties {
   public static final String PREFIX = "config.gateway.log.access";
   /**
    * 是否开启日志打印
    */
   private Boolean enabled = true;

   /**
    * 忽略的pattern
    */
   private List<String> ignoredPatterns;

   private ApiAlarmConfiguration fail = new ApiAlarmConfiguration();

   private SlowApiAlarmConfiguration slow = new SlowApiAlarmConfiguration();

   /**
    * 慢API报警配置
    */
   @Data
   public static class SlowApiAlarmConfiguration {

   	/**
   	 * 是否开启API慢日志打印
   	 */
   	private boolean alarm = true;

   	/**
   	 * 报警阈值 (单位:毫秒)
   	 */
   	private long threshold = 500;
   }


   /**
    * API异常报警(根据http状态码判定)
    */
   @Data
   public static class ApiAlarmConfiguration {

   	/**
   	 * 是否开启异常报警 默认关闭
   	 */
   	private boolean alarm = false;

   	/**
   	 * 排除状态码
   	 */
   	private List<Integer> exclusion;
   }
}

定义log实体

@Data
public class GatewayLog implements Serializable {
  	private static final long serialVersionUID = -3205904134722576668L;

    /**
     * 访问实例
	 */
	private String targetServer;

    /**
     * 请求路径
	 */
	private String requestPath;

    /**
     * 请求与方法
	 */
	private String method;

    /**
     * 请求协议
	 */
	private String schema;

    /**
     * 请求ip
	 */
	private String ip;

    /**
	 * 请求时间
	 */
	private Date requestTime;

	/**
	 * 请求参数
	 */
	private Map<String,String> queryParams;

    /**
     * 请求体
	 */
	private String requestBody;

	/**
	 * 请求执行时间
	 */
	private Long executeTime;

    /**
     * 请求类型
	 */
	private String requestContentType;

    /**
     * 相应状态码
	 */
	private int code;
}

定义相应日志工厂及常量

public interface GatewayLogType {
	/**
	 * 常规输出
	 */
	String APPLICATION_JSON_REQUEST = "applicationJsonRequest";

	String FORM_DATA_REQUEST = "formDataRequest";

	String BASIC_REQUEST = "basicRequest";

	String NORMAL_REQUEST = "normalRequest";

    /**
     * 慢查询
	 */
	String SLOW = "slow";

    /**
     * 非200响应
	 */
	String FAIL = "fail";
}


@Slf4j
public class GatewayLogInfoFactory {
	public static void log(String type, GatewayLog gatewayLog){
		switch (type){
			case GatewayLogType.APPLICATION_JSON_REQUEST:
				log.info("[{}] {} {},route: {},status: {},excute: {} mills,requestBody: {}"
						,gatewayLog.getIp()
						,gatewayLog.getMethod()
						,gatewayLog.getRequestPath()
						,gatewayLog.getTargetServer()
						,gatewayLog.getCode()
						,gatewayLog.getExecuteTime()
						,StrUtil.replace(gatewayLog.getRequestBody(), StrPool.LF,"")
				);
				break;
			case GatewayLogType.FORM_DATA_REQUEST:
				log.info("[{}] {} {},route: {},status: {},excute: {} mills,requestBody: {}"
						,gatewayLog.getIp()
						,gatewayLog.getMethod()
						,gatewayLog.getRequestPath()
						,gatewayLog.getTargetServer()
						,gatewayLog.getCode()
						,gatewayLog.getExecuteTime()
						,StrUtil.replace(gatewayLog.getRequestBody(), StrPool.LF,"")
				);
				break;
			case GatewayLogType.BASIC_REQUEST:
				log.info("[{}] {} {},route: {},status: {},excute: {} mills,requestBody: {}"
						,gatewayLog.getIp()
						,gatewayLog.getMethod()
						,gatewayLog.getRequestPath()
						,gatewayLog.getTargetServer()
						,gatewayLog.getCode()
						,gatewayLog.getExecuteTime()
						,StrUtil.replace(gatewayLog.getRequestBody(), StrPool.LF,"")
				);
				break;
			case GatewayLogType.NORMAL_REQUEST:
				log.info("[{}] {} {},route: {},status: {},excute: {} mills,queryParams: {}"
						,gatewayLog.getIp()
						,gatewayLog.getMethod()
						,gatewayLog.getRequestPath()
						,gatewayLog.getTargetServer()
						,gatewayLog.getCode()
						,gatewayLog.getExecuteTime()
						,gatewayLog.getQueryParams()
				);
				break;
			default:
				break;
		}
	}
}

定义日志全局过滤器文章来源地址https://www.toymoban.com/news/detail-506659.html

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import com.zkjc.xlcp.common.notifier.core.Notifier;
import com.zkjc.xlcp.gateway.log.GatewayLogInfoFactory;
import com.zkjc.xlcp.gateway.log.LogProperties;
import com.zkjc.xlcp.gateway.log.constant.GatewayLogType;
import com.zkjc.xlcp.gateway.log.entity.GatewayLog;
import com.zkjc.xlcp.gateway.util.IpUtil;
import io.netty.util.internal.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.CachedBodyOutputMessage;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.BodyInserterContext;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.multipart.FormFieldPart;
import org.springframework.http.codec.multipart.Part;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.*;

/**
 * @author likun
 * @date 2022年10月24日 9:52
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class AccessLogFilter implements GlobalFilter, Ordered {

	private final LogProperties logProperties;

	private final List<HttpMessageReader<?>> messageReaders = HandlerStrategies.withDefaults().messageReaders();

	/**
	 * default HttpMessageReader.
	 */
	private static final List<HttpMessageReader<?>> MESSAGE_READERS = HandlerStrategies.withDefaults().messageReaders();

	private final AntPathMatcher antPathMatcher = new AntPathMatcher();

	private final Notifier notifier;
	/*
	*  在CncloudRequestGlobalFilter后面执行 先清洗url在进行路径的日志的打印
	* */
	@Override
	public int getOrder() {
		return -100;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		// 判断是否打开相应是日志配置 ingore配置校验
		if (!logProperties.getEnabled()||hasIgnoredFlag(exchange,logProperties)){
			return chain.filter(exchange);
		}
		// 获得请求上下文
		GatewayLog gatewayLog = parseGateway(exchange);
		ServerHttpRequest request = exchange.getRequest();
		MediaType mediaType = request.getHeaders().getContentType();
		if (Objects.isNull(mediaType)){
			return writeNormalLog(exchange,chain,gatewayLog);
		}
		gatewayLog.setRequestContentType(mediaType.getType() + "/" + mediaType.getSubtype());
		// 对不同的请求类型做相应的处理
		if (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType)){
			return writeBodyLog(exchange,chain,gatewayLog);
		}else if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(mediaType) || MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(mediaType)){
			return readFormData(exchange,chain,gatewayLog);
		}else {
			return writeBasicLog(exchange,chain,gatewayLog);
		}
	}

	/**
	 * 校验白名单
	 * @param exchange
	 * @param logProperties
	 * @return
	 */
	private Boolean hasIgnoredFlag(ServerWebExchange exchange,LogProperties logProperties){
		List<String> ignoredPatterns = logProperties.getIgnoredPatterns();
		if (CollectionUtil.isEmpty(ignoredPatterns)){
			return Boolean.FALSE;
		}
		ServerHttpRequest request = exchange.getRequest();
		URI uri = request.getURI();
		for (String pattern : ignoredPatterns) {
			if (antPathMatcher.match(pattern,uri.getPath())){
				return Boolean.TRUE;
			}
		}
		return Boolean.FALSE;
	}

	/**
	 * 生成相应的报告并推送qq邮箱消息
	 */
	private void report(GatewayLog gatewayLog){
		if (notifier==null){
			return;
		}
		boolean reported = exceptionReport(gatewayLog);
		if (!reported){
			slowApiReport(gatewayLog);
		}
	}

	/**
	 * 异常报警
	 * @param gatewayLog
	 * @return
	 */
	private Boolean exceptionReport(GatewayLog gatewayLog){
		int code = gatewayLog.getCode();
		if (code==HttpStatus.OK.value()){
			return Boolean.FALSE;
		}
		LogProperties.ApiAlarmConfiguration apiAlarmConfiguration = logProperties.getFail();
		if (!apiAlarmConfiguration.isAlarm()){
			log.debug("api exception alarm disabled.");
			return Boolean.FALSE;
		}
		if (!CollectionUtils.isEmpty(apiAlarmConfiguration.getExclusion()) && apiAlarmConfiguration.getExclusion().contains(code)) {
			log.debug("status [{}] excluded.", code);
			return Boolean.FALSE;
		}
		String alarmContent = String.format("【API异常】 请求ip:[{%s}],请求路由:[{%s}],请求地址:[{%s}],返回状态码:[{%d}],执行时间:%d ms",gatewayLog.getIp(),gatewayLog.getTargetServer(),gatewayLog.getRequestPath(),code,gatewayLog.getExecuteTime());
		notifier.notify(alarmContent);
		return Boolean.TRUE;
	}

	private Boolean slowApiReport(GatewayLog gatewayLog){
		LogProperties.SlowApiAlarmConfiguration slowApiAlarmConfiguration = logProperties.getSlow();
		long threshold = slowApiAlarmConfiguration.getThreshold();
		if (gatewayLog.getExecuteTime()<threshold){
			return Boolean.FALSE;
		}
		if (!slowApiAlarmConfiguration.isAlarm()) {
			log.debug("slow api alarm disabled.");
			return Boolean.FALSE;
		}
		String slowContent = String.format("【API执行时间过长,超过设定阈值】 请求ip:[{%s}],请求路由:[{%s}],请求地址:[{%s}],执行时间:%d ms",gatewayLog.getIp(),gatewayLog.getTargetServer(),gatewayLog.getRequestPath(),gatewayLog.getExecuteTime());
		notifier.notify(slowContent);
		return Boolean.TRUE;
	}


	/**
	 * 获得当前请求分发的路由
	 * @param exchange
	 * @return
	 */
	private Route getGatewayRoute(ServerWebExchange exchange) {
		return exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
	}

	private GatewayLog parseGateway(ServerWebExchange exchange){
		ServerHttpRequest request = exchange.getRequest();
		String requestPath = request.getPath().pathWithinApplication().value();
		Route route = getGatewayRoute(exchange);
		String ip = IpUtil.getIpAddress(request);
		GatewayLog gatewayLog = new GatewayLog();
		gatewayLog.setSchema(request.getURI().getScheme());
		gatewayLog.setMethod(request.getMethodValue());
		gatewayLog.setRequestPath(requestPath);
		gatewayLog.setTargetServer(route.getId());
		gatewayLog.setIp(ip);
		gatewayLog.setRequestTime(new Date());
		return gatewayLog;
	}

	private Mono writeNormalLog(ServerWebExchange exchange, GatewayFilterChain chain, GatewayLog gatewayLog){
		return chain.filter(exchange).then(Mono.fromRunnable(()->{
			ServerHttpResponse response = exchange.getResponse();
			int value = response.getStatusCode().value();
			gatewayLog.setCode(value);
			long executeTime = DateUtil.between(gatewayLog.getRequestTime(), new Date(), DateUnit.MS);
			gatewayLog.setExecuteTime(executeTime);
			ServerHttpRequest request = exchange.getRequest();
			MultiValueMap<String, String> queryParams = request.getQueryParams();
			Map<String, String> paramsMap = new HashMap<>();
			if (CollectionUtil.isNotEmpty(queryParams)) {
				for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {
					paramsMap.put(entry.getKey(), StrUtil.join(StrPool.COMMA,entry.getValue()));
				}
			}
			gatewayLog.setQueryParams(paramsMap);
			GatewayLogInfoFactory.log(GatewayLogType.NORMAL_REQUEST,gatewayLog);
			// 推送相应的报告
			report(gatewayLog);
		}));
	}

	/**
	 * 解决 request body 只能读取一次问题,
	 * 参考: org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory
	 * @param exchange
	 * @param chain
	 * @param gatewayLog
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Mono writeBodyLog(ServerWebExchange exchange, GatewayFilterChain chain, GatewayLog gatewayLog) {
		ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
		Mono<String> modifiedBody = serverRequest.bodyToMono(String.class).flatMap(body -> {
			gatewayLog.setRequestBody(body);
			return Mono.just(body);
		});
		// 通过 BodyInserter 插入 body(支持修改body), 避免 request body 只能获取一次
		BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody, String.class);
		HttpHeaders headers = new HttpHeaders();
		headers.putAll(exchange.getRequest().getHeaders());
		// the new content type will be computed by bodyInserter
		// and then set in the request decorator
		headers.remove(HttpHeaders.CONTENT_LENGTH);
		CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);
		return bodyInserter.insert(outputMessage, new BodyInserterContext()).then(Mono.defer(() -> {                    // 重新封装请求
			ServerHttpRequest decoratedRequest = requestDecorate(exchange, headers, outputMessage);                    // 记录响应日志
			ServerHttpResponseDecorator decoratedResponse = recordResponseLog(exchange, gatewayLog);                    // 记录普通的
			return chain.filter(exchange.mutate().request(decoratedRequest).response(decoratedResponse).build()).then(Mono.fromRunnable(() -> {                                // 打印日志
				GatewayLogInfoFactory.log(GatewayLogType.APPLICATION_JSON_REQUEST,gatewayLog);
				// 推送相应的报告
				report(gatewayLog);
			}));
		}));
	}


	/**
	 * 读取form-data数据
	 * @param exchange
	 * @param chain
	 * @param accessLog
	 * @return
	 */
	private Mono<Void> readFormData(ServerWebExchange exchange, GatewayFilterChain chain, GatewayLog accessLog) {
		return DataBufferUtils.join(exchange.getRequest().getBody()).flatMap(dataBuffer -> {
			DataBufferUtils.retain(dataBuffer);
			final Flux<DataBuffer> cachedFlux = Flux.defer(() -> Flux.just(dataBuffer.slice(0, dataBuffer.readableByteCount())));
			final ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
				@Override
				public Flux<DataBuffer> getBody() {
					return cachedFlux;
				}
				@Override
				public MultiValueMap<String, String> getQueryParams() {
					return UriComponentsBuilder.fromUri(exchange.getRequest().getURI()).build().getQueryParams();
				}
			};
			final HttpHeaders headers = exchange.getRequest().getHeaders();
			if (headers.getContentLength() == 0) {
				return chain.filter(exchange);
			}
			ResolvableType resolvableType;
			if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(headers.getContentType())) {
				resolvableType = ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, Part.class);
			} else {
				//解析 application/x-www-form-urlencoded
				resolvableType = ResolvableType.forClass(String.class);
			}

			return MESSAGE_READERS.stream().filter(reader -> reader.canRead(resolvableType, mutatedRequest.getHeaders().getContentType())).findFirst().orElseThrow(() -> new IllegalStateException("no suitable HttpMessageReader.")).readMono(resolvableType, mutatedRequest, Collections.emptyMap()).flatMap(resolvedBody -> {
				if (resolvedBody instanceof MultiValueMap) {
					LinkedMultiValueMap map = (LinkedMultiValueMap) resolvedBody;
					if (CollectionUtil.isNotEmpty(map)) {
						StringBuilder builder = new StringBuilder();
						final Part bodyPartInfo = (Part) ((MultiValueMap) resolvedBody).getFirst("body");
						if (bodyPartInfo instanceof FormFieldPart) {
							String body = ((FormFieldPart) bodyPartInfo).value();
							builder.append("body=").append(body);
						}
						accessLog.setRequestBody(builder.toString());
					}
				} else {
					accessLog.setRequestBody((String) resolvedBody);
				}

				//获取响应体
				ServerHttpResponseDecorator decoratedResponse = recordResponseLog(exchange, accessLog);
				return chain.filter(exchange.mutate().request(mutatedRequest).response(decoratedResponse).build()).then(Mono.fromRunnable(() -> {                                    // 打印日志
					// 打印响应的日志
					GatewayLogInfoFactory.log(GatewayLogType.FORM_DATA_REQUEST,accessLog);
					// 推送相应的报告
					report(accessLog);
				}));
			});
		});
	}


	private Mono<Void> writeBasicLog(ServerWebExchange exchange, GatewayFilterChain chain, GatewayLog accessLog) {
		return DataBufferUtils.join(exchange.getRequest().getBody()).flatMap(dataBuffer -> {
			DataBufferUtils.retain(dataBuffer);
			final Flux<DataBuffer> cachedFlux = Flux.defer(() -> Flux.just(dataBuffer.slice(0, dataBuffer.readableByteCount())));
			final ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
				@Override
				public Flux<DataBuffer> getBody() {
					return cachedFlux;
				}

				@Override
				public MultiValueMap<String, String> getQueryParams() {
					return UriComponentsBuilder.fromUri(exchange.getRequest().getURI()).build().getQueryParams();
				}
			};
			StringBuilder builder = new StringBuilder();
			MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
			if (CollectionUtil.isNotEmpty(queryParams)) {
				for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {
					builder.append(entry.getKey()).append("=").append(entry.getValue()).append(StrPool.COMMA);
				}
			}
			accessLog.setRequestBody(builder.toString());            //获取响应体
			ServerHttpResponseDecorator decoratedResponse = recordResponseLog(exchange, accessLog);
			return chain.filter(exchange.mutate().request(mutatedRequest).response(decoratedResponse).build()).then(Mono.fromRunnable(() -> {                        // 打印日志
				GatewayLogInfoFactory.log(GatewayLogType.BASIC_REQUEST,accessLog);
				// 推送相应的报告
				report(accessLog);
			}));
		});
	}

	/**
	 * 请求装饰器,重新计算 headers
	 * @param exchange
	 * @param headers
	 * @param outputMessage
	 * @return
	 */
	private ServerHttpRequestDecorator requestDecorate(ServerWebExchange exchange, HttpHeaders headers, CachedBodyOutputMessage outputMessage) {
		return new ServerHttpRequestDecorator(exchange.getRequest()) {
			@Override
			public HttpHeaders getHeaders() {
				long contentLength = headers.getContentLength();
				HttpHeaders httpHeaders = new HttpHeaders();
				httpHeaders.putAll(super.getHeaders());
				if (contentLength > 0) {
					httpHeaders.setContentLength(contentLength);
				} else {
					httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
				}
				return httpHeaders;
			}
			@Override
			public Flux<DataBuffer> getBody() {
				return outputMessage.getBody();
			}
		};
	}

	/**
	 * 记录响应日志
	 * 通过 DataBufferFactory 解决响应体分段传输问题。
	 */
	private ServerHttpResponseDecorator recordResponseLog(ServerWebExchange exchange, GatewayLog gatewayLog) {
		ServerHttpResponse response = exchange.getResponse();
		DataBufferFactory bufferFactory = response.bufferFactory();
		return new ServerHttpResponseDecorator(response) {
			@Override
			public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
				if (body instanceof Flux) {
					// 计算执行时间
					long executeTime = DateUtil.between(gatewayLog.getRequestTime(), new Date(), DateUnit.MS);
					gatewayLog.setExecuteTime(executeTime);
					// 获取响应类型,如果是 json 就打印
					String originalResponseContentType = exchange.getAttribute(ServerWebExchangeUtils.ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR);//
					gatewayLog.setCode(this.getStatusCode().value());
					//
					if (Objects.equals(this.getStatusCode(), HttpStatus.OK)
							&& !StringUtil.isNullOrEmpty(originalResponseContentType)
							&& originalResponseContentType.contains("application/json")) {
						Flux<? extends DataBuffer> fluxBody = Flux.from(body);
						return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
							// 合并多个流集合,解决返回体分段传输
							DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
							DataBuffer join = dataBufferFactory.join(dataBuffers);
							byte[] content = new byte[join.readableByteCount()];
							// 释放掉内存
							join.read(content);
							DataBufferUtils.release(join);
							return bufferFactory.wrap(content);
						}));
					}else {

					}
				}
				return super.writeWith(body);
			}
		};
	}
}

到了这里,关于基于Spring-cloud-gateway实现全局日志记录的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring-Cloud-Gateway如何自定义路由过滤器?

    遇到这么一个面试题:自定义网关过滤器实现把url中的请求参数放到http的header中传递给微服务。 我们知道网关的一个重要的作用就是路由转发,路由表的配置大概是这个样子: 其中的filters就是配置的路由过滤器,Spring已经内置了31个路由的过滤器,这些过滤器都是 org.spring

    2024年02月16日
    浏览(40)
  • 芝法酱躺平攻略(14)——Nginx与Spring-Cloud-Gateway

    上一章芝法酱躺平攻略(12)展望了微服务下常见的技术需求与常见解决方案,本期来讲解第一部分,Nginx与SpringCloud-Gateway。 本章将实践在nginx和spring-cloud-gateway的简单使用。 首先,去官网查找最新稳定版,把下载的nginx包放到DOWNLOAD文件夹下。 而后把该包解压到SOFTWARE文件夹

    2024年02月07日
    浏览(43)
  • Spring-Cloud-Gateway修改请求(json,form带文件请求)参数,返回值参数

    新项目需要在getway统一做入参、出参加解密,记录日志。记录一下form,x-www-form-urlencoded , json 这几种修改数据的方式。 gateway做拦截器是实现GlobalFilter接口,修改json方式网上有很多文章,后来又想研究研究能不能实现修改form-data参数,以及文件请求,后者文章不多大部分是怎

    2024年02月16日
    浏览(47)
  • Spring Cloud GateWay 全局过滤器

    这是一个自定义的 Spring Cloud Gateway 全局过滤器(Global Filter)。在 Spring Cloud Gateway 中,全局过滤器可以在请求被路由到目标服务之前或之后执行一些操作。这个过滤器实现了 GlobalFilter 接口和 Ordered 接口,这两个接口的作用如下: GlobalFilter 接口: 这是一个 Spring Cloud Gateway 提

    2024年02月11日
    浏览(46)
  • Spring Cloud Gateway GlobalFilter(全局过滤器)详解(官方原版)

    GlobalFilter接口具有与GatewayFilter相同的签名。这些是有条件地应用于所有路由的特殊过滤器。 当请求与路由匹配时,过滤web处理程序会将GlobalFilter的所有实例和GatewayFilter的所有路由特定实例添加到过滤器链中。这个组合过滤器链由org.springframework.core.Ordered接口排序,您可以通

    2024年02月09日
    浏览(44)
  • 【Spring Cloud】深入探索统一网关 Gateway 的搭建,断言工厂,过滤器工厂,全局过滤器以及跨域问题

    在微服务架构中,网关是至关重要的组件,具有多重职责,为整个系统提供了一系列关键功能。从下面的微服务结构图中,我们可以明确网关的几项主要作用: 微服务结构图: 请求过滤与安全: 用户的所有请求首先经过网关,这使得网关成为系统的第一道防线。通过对传入

    2024年02月07日
    浏览(57)
  • Spring Cloud Gateway 实现原理

    Spring Cloud Gateway是Spring Cloud生态系统中的一个组件,用于构建基于Spring Boot的微服务架构中的网关服务。它的主要目的是提供一种灵活的方式来路由、过滤和转换HTTP请求,从而允许您构建强大、高性能的微服务应用程序。 以下是Spring Cloud Gateway的一些核心原理和功能: 路由(

    2024年02月10日
    浏览(39)
  • Spring Cloud GateWay实现熔断降级

    当分布式系统中的网关接收到大量请求并向后端远程系统或服务发起调用时,后端服务可能会产生调用失败(如超时或异常)。这时,如果让请求继续堆积在网关上,可能会导致整个系统的瘫痪。因此,需要快速失败并返回请求,这就是所谓的熔断。 降级是指在系统资源不足

    2024年02月02日
    浏览(41)
  • Spring Cloud Gateway实现灰度发布功能

    灰度发布又名金丝雀发布,在微服务中的表现为同一服务同时上线不同版本,让一部分用户使用新版本来验证新特性,如果验证没有问题,则将所有用户都迁移到新版本上。 在微服务架构中,网关负责请求的统一入口,主要功能之一是请求路由。而灰度发布实质就是让指定用

    2024年02月21日
    浏览(81)
  • Spring Cloud Gateway 网关实现白名单功能

    1 摘要 对于微服务后台而言,网关层作为所有网络请求的入口。一般基于安全考虑,会在网关层做权限认证,但是对于一些例如登录、注册等接口以及一些资源数据,这些是不需要有认证信息,因此需要在网关层设计一个白名单的功能。本文将基于 Spring Cloud Gateway 2.X 实现白

    2023年04月08日
    浏览(43)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包