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应用中出现的Full GC问题的场景与解决

《SpringBoot应用中出现的FullGC问题的场景与解决》这篇文章主要为大家详细介绍了SpringBoot应用中出现的FullGC问题的场景与解决方法,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录Full GC的原理与触发条件原理触发条件对Spring Boot应用的影响示例代码优化建议结论F

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll

SpringBoot条件注解核心作用与使用场景详解

《SpringBoot条件注解核心作用与使用场景详解》SpringBoot的条件注解为开发者提供了强大的动态配置能力,理解其原理和适用场景是构建灵活、可扩展应用的关键,本文将系统梳理所有常用的条件注... 目录引言一、条件注解的核心机制二、SpringBoot内置条件注解详解1、@ConditionalOn

通过Spring层面进行事务回滚的实现

《通过Spring层面进行事务回滚的实现》本文主要介绍了通过Spring层面进行事务回滚的实现,包括声明式事务和编程式事务,具有一定的参考价值,感兴趣的可以了解一下... 目录声明式事务回滚:1. 基础注解配置2. 指定回滚异常类型3. ​不回滚特殊场景编程式事务回滚:1. ​使用 TransactionT

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

SpringSecurity JWT基于令牌的无状态认证实现

《SpringSecurityJWT基于令牌的无状态认证实现》SpringSecurity中实现基于JWT的无状态认证是一种常见的做法,本文就来介绍一下SpringSecurityJWT基于令牌的无... 目录引言一、JWT基本原理与结构二、Spring Security JWT依赖配置三、JWT令牌生成与

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

如何配置Spring Boot中的Jackson序列化

《如何配置SpringBoot中的Jackson序列化》在开发基于SpringBoot的应用程序时,Jackson是默认的JSON序列化和反序列化工具,本文将详细介绍如何在SpringBoot中配置... 目录配置Spring Boot中的Jackson序列化1. 为什么需要自定义Jackson配置?2.

Java中使用Hutool进行AES加密解密的方法举例

《Java中使用Hutool进行AES加密解密的方法举例》AES是一种对称加密,所谓对称加密就是加密与解密使用的秘钥是一个,下面:本文主要介绍Java中使用Hutool进行AES加密解密的相关资料... 目录前言一、Hutool简介与引入1.1 Hutool简介1.2 引入Hutool二、AES加密解密基础