Spring Cloud Feign 之日志自定義擴展

timg.jpeg

Spring Cloud Feign 之日志自定義擴展

遷移到CSDN
環境信息: java 1.8、Spring boot 1.5.10.RELEASE、spring cloud-Edgware.SR3、maven 3.3+

第二章 Spring Cloud Feign 之日志輸出已經對Feign自帶的日志輸出說明,與外部HTTP接口交互時需要記錄一些請求和響應日志來排查問題,雖然Feign支持但它的日志是Debug級別,并不符合我們在生產中使用INFO級別日志要求,所以這章介紹下自定義日志輸出。

分析Spring Cloud Feign 默認日志

首先看下spring cloud feign 對日志輸出的處理

package org.springframework.cloud.netflix.feign;

import feign.Logger;

/**
 * Allows an application to use a custom Feign {@link Logger}.
 *
 * @author Venil Noronha
 */
public interface FeignLoggerFactory {

   /**
    * Factory method to provide a {@link Logger} for a given {@link Class}.
    *
    * @param type the {@link Class} for which a {@link Logger} instance is to be created
    * @return a {@link Logger} instance
    */
   public Logger create(Class<?> type);

}

通過源碼我們知道spring cloud feign 已經對feign的日志輸出這塊做了擴展,當然feign本身也可以,這里針對spring cloud feign 進行講解。

FeignLoggerFactory是Feign日志工廠接口類,DefaultFeignLoggerFactory是它的默認實現,spring cloud feign 就是用的 DefaultFeignLoggerFactory

@Override
public Logger create(Class<?> type) {
   return this.logger != null ? this.logger : new Slf4jLogger(type);
}

默認日志工廠使用Slf4jLogger日志,然后我們看下源碼

package feign.slf4j;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import feign.Request;
import feign.Response;

public class Slf4jLogger extends feign.Logger {

  private final Logger logger;

  public Slf4jLogger() {
    this(feign.Logger.class);
  }

  public Slf4jLogger(Class<?> clazz) {
    this(LoggerFactory.getLogger(clazz));
  }

  public Slf4jLogger(String name) {
    this(LoggerFactory.getLogger(name));
  }

  Slf4jLogger(Logger logger) {
    this.logger = logger;
  }

  @Override
  protected void logRequest(String configKey, Level logLevel, Request request) {
    if (logger.isDebugEnabled()) {
      super.logRequest(configKey, logLevel, request);
    }
  }
    
  @Override
  protected Response logAndRebufferResponse(String configKey, Level logLevel, 
                                      Response response,long elapsedTime) throws IOException {
    if (logger.isDebugEnabled()) {
      return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime);
    }
    return response;
  }

  @Override
  protected void log(String configKey, String format, Object... args) {
    // Not using SLF4J's support for parameterized messages (even though it would be more efficient) because it would
    // require the incoming message formats to be SLF4J-specific.
    if (logger.isDebugEnabled()) {
      logger.debug(String.format(methodTag(configKey) + format, args));
    }
  }
}

看到這里就知道為什么Spring Cloud Feign 日志輸出的是Debug級別日志了。

自定Spring Cloud Feign日志輸出

參考DefaultFeignLoggerFactory類實現自己的日志工廠實現類。

場景說明:將原有的debug級別,修改成info級別

第一步:實現FeignLoggerFactory工廠接口,InfoFeignLoggerFactoryFeignConfig靜態內部類

/**
 * feign info 日志工廠
 */
public static class InfoFeignLoggerFactory implements FeignLoggerFactory {

    @Override
    public Logger create(Class<?> type) {
        return new InfoFeignLogger(LoggerFactory.getLogger(type));
    }
}

第二部: 繼承feign.Logger實現info級別日志輸出,InfoFeignLogger使用slf4j日志工具,此處只是簡單的實現了info級別日志輸出,如果想效率更高請參考Slf4jLogger添加一些日記級別判斷

/**
 * info feign 日志
 * @author: sunshaoping
 * @date: Create by in 下午3:29 2018/8/8
 */
public class InfoFeignLogger extends feign.Logger {

    private final Logger logger;

    public InfoFeignLogger(Logger logger) {
        this.logger = logger;
    }

    @Override
    protected void log(String configKey, String format, Object... args) {
        if (logger.isInfoEnabled()) {
            logger.info(String.format(methodTag(configKey) + format, args));
        }
    }
}

第三部:日志工廠InfoFeignLoggerFactory注冊到spring 容器中,使用spring java Config

/**
 * feign 配置
 * @author: sunshaoping
 * @date: Create by in 下午4:07 2018/8/7
 */
@Configuration
public class FeignConfig {

    @Bean
    Logger.Level feignLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    FeignLoggerFactory infoFeignLoggerFactory() {
        return new InfoFeignLoggerFactory();
    }

}

這樣就實現了自定義的日志打印了,簡單吧,讓我們看看效果,是不是變成INFO日志級別了。

2018-08-08 15:45:39.261  INFO 3514 --- [           main] com.example.feign.UserFeign              : [UserFeign#save] ---> POST http://localhost:8080/user HTTP/1.1
2018-08-08 15:45:39.262  INFO 3514 --- [           main] com.example.feign.UserFeign              : [UserFeign#save] Content-Type: application/json;charset=UTF-8
2018-08-08 15:45:39.262  INFO 3514 --- [           main] com.example.feign.UserFeign              : [UserFeign#save] Content-Length: 27
2018-08-08 15:45:39.262  INFO 3514 --- [           main] com.example.feign.UserFeign              : [UserFeign#save] 
2018-08-08 15:45:39.262  INFO 3514 --- [           main] com.example.feign.UserFeign              : [UserFeign#save] {"id":null,"name":"張三"}
2018-08-08 15:45:39.263  INFO 3514 --- [           main] com.example.feign.UserFeign              : [UserFeign#save] ---> END HTTP (27-byte body)
2018-08-08 15:45:39.691  INFO 3514 --- [           main] com.example.feign.UserFeign              : [UserFeign#save] <--- HTTP/1.1 200 (427ms)
2018-08-08 15:45:39.691  INFO 3514 --- [           main] com.example.feign.UserFeign              : [UserFeign#save] content-length: 0
2018-08-08 15:45:39.691  INFO 3514 --- [           main] com.example.feign.UserFeign              : [UserFeign#save] date: Wed, 08 Aug 2018 07:45:39 GMT
2018-08-08 15:45:39.691  INFO 3514 --- [           main] com.example.feign.UserFeign              : [UserFeign#save] 
2018-08-08 15:45:39.692  INFO 3514 --- [           main] com.example.feign.UserFeign              : [UserFeign#save] <--- END HTTP (0-byte body)

細心的同學可能會發現,為什么我們的FeignLoggerFactory就起作用了,其實這是spring 強大的條件裝配功能

FeignLoggerFactory不存在時才加載默認DefaultFeignLoggerFactory,如果對spring 條件裝配感興趣的同學可以看下官網,spring boot對spring條件裝配擴展了很多注解。

@Bean
@ConditionalOnMissingBean(FeignLoggerFactory.class)
public FeignLoggerFactory feignLoggerFactory() {
   return new DefaultFeignLoggerFactory(logger);
}

總結

此章節介紹了自定義Feign 日志輸出,通過實現FeignLoggerFactory工廠類接口和繼承feign.Logger類,還使用了 slf4j日志工具,在項目開發過程中建議使用slf4j這樣項目在更換日志框架也不用修改源代碼了,擴展性更強。

樣例地址 spring-cloud-feign 分支 Spring-Cloud-Feign之日志自定義擴展

寫在最后

Spring Cloud Feign 系列持續更新中。。。。。歡迎關注

如發現哪些知識點有誤或是沒有看懂,歡迎在評論區提出,博主及時改正。

歡迎轉載請注明出處。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容