spring_cloud_feign_log

2024-08-22 07:18
文章标签 java spring cloud feign log

本文主要是介绍spring_cloud_feign_log,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这篇主要介绍一下spring cloud feign log的相关知识点。

下面以一个项目中的具体例子来说明:

下面是一个接口,在a服务中通过feign去调用b服务的generateBizNo接口,最后返回b服务的generateBizNo所返回的响应。

@FeignClient(value = "serviceName", url = "serviceUrl", fallbackFactory = FeignFallbackFactory.class,configuration = FeignLogConfiguration.class
)
public interface IOuterXXService extends BaseFeignClient {@RequestMapping(value = "/xx/yy", method = RequestMethod.POST)ResultBase<String> generateBizNo(XXX var1);
}

那么,如何来打印出这个feign调用的接口的相关日志呢?

  • 使用log去该接口的实现类的方法调用开始和结束打印日志?
  • 使用切面去打印日志?
  • 还有其他???

这里我介绍的是使用spring cloudfeign log来打印feign接口调用日志,效果图如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-siEil36M-1602235194448)(/Users/yongyongli/msad_document/documents/image-20201009164140207.png)]

通过上图我们可以看到feign log的日志输出有如下的信息:

  • 接口调用的方法及域名
  • http协议
  • 请求的头信息content-type以及content-length
  • 入参报文和相应报文,都是json格式
  • 请求耗时以及响应的状态码
  • 请求应用的名称以及端口号

下面是关于spring cloud feign log的相关知识点和如何才可以做出上面的效果:

首先,需要增加一个配置类:

package com.xxx.xxx.xxx.spi.configuration;import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @author lee* @date 2020/10/9***/
@Configuration
public class FeignLogConfiguration {@BeanLogger.Level feignLoggerLevel(){// 设置feign打印的log级别,此处的full代表的是信息全部打印,此log level非彼log levelreturn Logger.Level.FULL;}
}

第二步,在你使用@FeignClient的注解的时候,里面新增属性configuration=FeignLogConfiguration.class

@FeignClient(value = "serviceName", url = "serviceUrl", fallbackFactory = FeignFallbackFactory.class,configuration = FeignLogConfiguration.class
)

第三步,需要进行一些配置,我们使用的是nacos,所以在a服务的配置文件中新增如下的配置信息:

logging:level:com:xxx:yyy: DEBUG

需要注意的是logginglevel两个层级是必须配置的,其他层级就是包路径,此处是日志的级别,需要设置为DEBUG,才可以生效。

到这里,基本就可以实现上面的效果了。

接下来说一下相关的知识点:

Loggerfeign包下的一个抽象类,位于

<dependency><groupId>io.github.openfeign</groupId><artifactId>feign-core</artifactId>
</dependency>

存在一个枚举Level,里面四个枚举项:

  • NONE:不打印日志
  • BASIC:只打印请求方法和url,以及响应状态码和执行时间
  • FULL:打印头信息,请求体,响应豹纹和元数据
  • HEADERS:打印基本的请求和响应头信息

其中存在一个logRequest的方法用来处理请求,logAndRebufferResponse来处理响应报文。

具体的源码如下所示:

package feign;import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.FileHandler;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;import static feign.Util.UTF_8;
import static feign.Util.decodeOrDefault;
import static feign.Util.valuesOrEmpty;/*** Simple logging abstraction for debug messages.  Adapted from {@code retrofit.RestAdapter.Log}.*/
public abstract class Logger {protected static String methodTag(String configKey) {return new StringBuilder().append('[').append(configKey.substring(0, configKey.indexOf('('))).append("] ").toString();}/*** Override to log requests and responses using your own implementation. Messages will be http* request and response text.** @param configKey value of {@link Feign#configKey(Class, java.lang.reflect.Method)}* @param format    {@link java.util.Formatter format string}* @param args      arguments applied to {@code format}*/protected abstract void log(String configKey, String format, Object... args);protected void logRequest(String configKey, Level logLevel, Request request) {log(configKey, "---> %s %s HTTP/1.1", request.method(), request.url());if (logLevel.ordinal() >= Level.HEADERS.ordinal()) {for (String field : request.headers().keySet()) {for (String value : valuesOrEmpty(request.headers(), field)) {log(configKey, "%s: %s", field, value);}}int bodyLength = 0;if (request.body() != null) {bodyLength = request.body().length;if (logLevel.ordinal() >= Level.FULL.ordinal()) {StringbodyText =request.charset() != null ? new String(request.body(), request.charset()) : null;log(configKey, ""); // CRLFlog(configKey, "%s", bodyText != null ? bodyText : "Binary data");}}log(configKey, "---> END HTTP (%s-byte body)", bodyLength);}}protected void logRetry(String configKey, Level logLevel) {log(configKey, "---> RETRYING");}protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response,long elapsedTime) throws IOException {String reason = response.reason() != null && logLevel.compareTo(Level.NONE) > 0 ?" " + response.reason() : "";int status = response.status();log(configKey, "<--- HTTP/1.1 %s%s (%sms)", status, reason, elapsedTime);if (logLevel.ordinal() >= Level.HEADERS.ordinal()) {for (String field : response.headers().keySet()) {for (String value : valuesOrEmpty(response.headers(), field)) {log(configKey, "%s: %s", field, value);}}int bodyLength = 0;if (response.body() != null && !(status == 204 || status == 205)) {// HTTP 204 No Content "...response MUST NOT include a message-body"// HTTP 205 Reset Content "...response MUST NOT include an entity"if (logLevel.ordinal() >= Level.FULL.ordinal()) {log(configKey, ""); // CRLF}byte[] bodyData = Util.toByteArray(response.body().asInputStream());bodyLength = bodyData.length;if (logLevel.ordinal() >= Level.FULL.ordinal() && bodyLength > 0) {log(configKey, "%s", decodeOrDefault(bodyData, UTF_8, "Binary data"));}log(configKey, "<--- END HTTP (%s-byte body)", bodyLength);return response.toBuilder().body(bodyData).build();} else {log(configKey, "<--- END HTTP (%s-byte body)", bodyLength);}}return response;}protected IOException logIOException(String configKey, Level logLevel, IOException ioe, long elapsedTime) {log(configKey, "<--- ERROR %s: %s (%sms)", ioe.getClass().getSimpleName(), ioe.getMessage(),elapsedTime);if (logLevel.ordinal() >= Level.FULL.ordinal()) {StringWriter sw = new StringWriter();ioe.printStackTrace(new PrintWriter(sw));log(configKey, sw.toString());log(configKey, "<--- END ERROR");}return ioe;}/*** Controls the level of logging.*/public enum Level {/*** No logging.*/NONE,/*** Log only the request method and URL and the response status code and execution time.*/BASIC,/*** Log the basic information along with request and response headers.*/HEADERS,/*** Log the headers, body, and metadata for both requests and responses.*/FULL}/*** Logs to System.err.*/public static class ErrorLogger extends Logger {@Overrideprotected void log(String configKey, String format, Object... args) {System.err.printf(methodTag(configKey) + format + "%n", args);}}/*** Logs to the category {@link Logger} at {@link java.util.logging.Level#FINE}, if loggable.*/public static class JavaLogger extends Logger {final java.util.logging.Loggerlogger =java.util.logging.Logger.getLogger(Logger.class.getName());@Overrideprotected void logRequest(String configKey, Level logLevel, Request request) {if (logger.isLoggable(java.util.logging.Level.FINE)) {super.logRequest(configKey, logLevel, request);}}@Overrideprotected Response logAndRebufferResponse(String configKey, Level logLevel, Response response,long elapsedTime) throws IOException {if (logger.isLoggable(java.util.logging.Level.FINE)) {return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime);}return response;}@Overrideprotected void log(String configKey, String format, Object... args) {if (logger.isLoggable(java.util.logging.Level.FINE)) {logger.fine(String.format(methodTag(configKey) + format, args));}}/*** Helper that configures java.util.logging to sanely log messages at FINE level without additional* formatting.*/public JavaLogger appendToFile(String logfile) {logger.setLevel(java.util.logging.Level.FINE);try {FileHandler handler = new FileHandler(logfile, true);handler.setFormatter(new SimpleFormatter() {@Overridepublic String format(LogRecord record) {return String.format("%s%n", record.getMessage()); // NOPMD}});logger.addHandler(handler);} catch (IOException e) {throw new IllegalStateException("Could not add file handler.", e);}return this;}}public static class NoOpLogger extends Logger {@Overrideprotected void logRequest(String configKey, Level logLevel, Request request) {}@Overrideprotected Response logAndRebufferResponse(String configKey, Level logLevel, Response response,long elapsedTime) throws IOException {return response;}@Overrideprotected void log(String configKey, String format, Object... args) {}}
}

最后说一下整个的调用链路:

在这里插入图片描述

为什么配置log的级别为debug,需要看看Slf4jLogger类对requestresponse请求响应报文的处理。

关于spring cloud feign log的相关知识介绍到这里,如果本文存在不对之处,麻烦指点批评。

在这里插入图片描述

这篇关于spring_cloud_feign_log的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1095599

相关文章

聊聊springboot中如何自定义消息转换器

《聊聊springboot中如何自定义消息转换器》SpringBoot通过HttpMessageConverter处理HTTP数据转换,支持多种媒体类型,接下来通过本文给大家介绍springboot中... 目录核心接口springboot默认提供的转换器如何自定义消息转换器Spring Boot 中的消息

Springboot项目构建时各种依赖详细介绍与依赖关系说明详解

《Springboot项目构建时各种依赖详细介绍与依赖关系说明详解》SpringBoot通过spring-boot-dependencies统一依赖版本管理,spring-boot-starter-w... 目录一、spring-boot-dependencies1.简介2. 内容概览3.核心内容结构4.

Spring Boot 整合 SSE(Server-Sent Events)实战案例(全网最全)

《SpringBoot整合SSE(Server-SentEvents)实战案例(全网最全)》本文通过实战案例讲解SpringBoot整合SSE技术,涵盖实现原理、代码配置、异常处理及前端交互,... 目录Spring Boot 整合 SSE(Server-Sent Events)1、简述SSE与其他技术的对

Spring Security 前后端分离场景下的会话并发管理

《SpringSecurity前后端分离场景下的会话并发管理》本文介绍了在前后端分离架构下实现SpringSecurity会话并发管理的问题,传统Web开发中只需简单配置sessionManage... 目录背景分析传统 web 开发中的 sessionManagement 入口ConcurrentSess

Java整合Protocol Buffers实现高效数据序列化实践

《Java整合ProtocolBuffers实现高效数据序列化实践》ProtocolBuffers是Google开发的一种语言中立、平台中立、可扩展的结构化数据序列化机制,类似于XML但更小、更快... 目录一、Protocol Buffers简介1.1 什么是Protocol Buffers1.2 Pro

Java实现本地缓存的四种方法实现与对比

《Java实现本地缓存的四种方法实现与对比》本地缓存的优点就是速度非常快,没有网络消耗,本地缓存比如caffine,guavacache这些都是比较常用的,下面我们来看看这四种缓存的具体实现吧... 目录1、HashMap2、Guava Cache3、Caffeine4、Encache本地缓存比如 caff

MyBatis-Plus 与 Spring Boot 集成原理实战示例

《MyBatis-Plus与SpringBoot集成原理实战示例》MyBatis-Plus通过自动配置与核心组件集成SpringBoot实现零配置,提供分页、逻辑删除等插件化功能,增强MyBa... 目录 一、MyBATis-Plus 简介 二、集成方式(Spring Boot)1. 引入依赖 三、核心机制

Java高效实现Word转PDF的完整指南

《Java高效实现Word转PDF的完整指南》这篇文章主要为大家详细介绍了如何用Spire.DocforJava库实现Word到PDF文档的快速转换,并解析其转换选项的灵活配置技巧,希望对大家有所帮助... 目录方法一:三步实现核心功能方法二:高级选项配置性能优化建议方法补充ASPose 实现方案Libre

springboot整合mqtt的步骤示例详解

《springboot整合mqtt的步骤示例详解》MQTT(MessageQueuingTelemetryTransport)是一种轻量级的消息传输协议,适用于物联网设备之间的通信,本文介绍Sprin... 目录1、引入依赖包2、yml配置3、创建配置4、自定义注解6、使用示例使用场景:mqtt可用于消息发

Java List 使用举例(从入门到精通)

《JavaList使用举例(从入门到精通)》本文系统讲解JavaList,涵盖基础概念、核心特性、常用实现(如ArrayList、LinkedList)及性能对比,介绍创建、操作、遍历方法,结合实... 目录一、List 基础概念1.1 什么是 List?1.2 List 的核心特性1.3 List 家族成