Feign Client 请求和响应以及 URL 日志记录

Ram*_*sar 7 logging request interceptor feign

如何记录Feign客户端请求、响应和 URL的负载。我必须实现拦截器吗?因为我的要求是在数据库的特殊表上记录请求和响应。

Pra*_*ran 23

Feign 具有开箱即用的日志记录机制,可以通过简单的步骤实现。

如果您使用的是 spring-cloud-starter-feign

FeignSlf4jLogger用于日志记录。Feign 日志记录文档

根据文档,可以配置以下日志记录级别,

  • NONE - 无日志记录(默认)。
  • BASIC - 仅记录请求方法和 URL 以及响应状态代码和执行时间。
  • HEADERS - 记录基本信息以及请求和响应标头。
  • FULL - 记录请求和响应的标头、正文和元数据。

注入Logger.Levelbean 就足够了。

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.BASIC;
    }
Run Code Online (Sandbox Code Playgroud)

或者

如果您更喜欢使用配置属性来配置 all @FeignClient,您可以使用默认的伪装名称创建配置属性。

feign:
  client:
    config:
      default:
        loggerLevel: basic
Run Code Online (Sandbox Code Playgroud)

如果您正在使用 'io.github.openfeign:feign-core'

如果您正在构建 Feign 构建器,那么您可以提及logLevel(Level.BASIC)

Feign.builder()
    .logger(new Slf4jLogger())
    .logLevel(Level.BASIC)
    .target(SomeFeignClient.class, url);
Run Code Online (Sandbox Code Playgroud)

我们可以灵活地自定义日志消息

默认的 feign 请求和响应日志记录

请求日志记录

响应日志

我们可以通过覆盖Logger#logRequestLogger#logAndRebufferResponse方法自定义伪装请求、响应日志记录模式。在以下示例中,我们自定义了请求日志记录模式

log(configKey, "---> %s %s HTTP/1.1 (%s-byte body) ", request.httpMethod().name(), request.url(), bodyLength);
Run Code Online (Sandbox Code Playgroud)

和响应日志记录模式

log(configKey, "<--- %s %s HTTP/1.1 %s (%sms) ", request.httpMethod().name(), request.url(), status, elapsedTime);
Run Code Online (Sandbox Code Playgroud)

完整的例子是


import feign.Logger;
import feign.Request;
import feign.Response;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

import static feign.Logger.Level.HEADERS;

@Slf4j
public class CustomFeignRequestLogging extends Logger {

    @Override
    protected void logRequest(String configKey, Level logLevel, Request request) {

        if (logLevel.ordinal() >= HEADERS.ordinal()) {
            super.logRequest(configKey, logLevel, request);
        } else {
            int bodyLength = 0;
            if (request.requestBody().asBytes() != null) {
                bodyLength = request.requestBody().asBytes().length;
            }
            log(configKey, "---> %s %s HTTP/1.1 (%s-byte body) ", request.httpMethod().name(), request.url(), bodyLength);
        }
    }

    @Override
    protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, long elapsedTime)
            throws IOException {
        if (logLevel.ordinal() >= HEADERS.ordinal()) {
            super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime);
        } else {
            int status = response.status();
            Request request = response.request();
            log(configKey, "<--- %s %s HTTP/1.1 %s (%sms) ", request.httpMethod().name(), request.url(), status, elapsedTime);
        }
        return response;
    }


    @Override
    protected void log(String configKey, String format, Object... args) {
        log.debug(format(configKey, format, args));
    }

    protected String format(String configKey, String format, Object... args) {
        return String.format(methodTag(configKey) + format, args);
    }
}

Run Code Online (Sandbox Code Playgroud)

注意: 可以轻松记录请求负载

String bodyText =
              request.charset() != null ? new String(request.body(), request.charset()) : null;
Run Code Online (Sandbox Code Playgroud)

但是在读取输入流后要小心编写响应负载,Util.toByteArray(response.body().asInputStream())然后您必须再次构建响应,如response.toBuilder().body(bodyData).build(). 否则,你最终会得到期望。原因是响应流在返回之前被读取并且总是关闭,这就是为什么该方法被命名为logAndRebufferResponse

如何使用自定义CustomFeignRequestLogging

如果您正在使用仅构建假客户端 'io.github.openfeign:feign-core'

Feign.builder()
     .logger(new CustomFeignRequestLogging())
     .logLevel(feign.Logger.Level.BASIC);

Run Code Online (Sandbox Code Playgroud)

如果您正在使用 'org.springframework.cloud:spring-cloud-starter-openfeign'

@Configuration
public class FeignLoggingConfiguration {

    @Bean
    public CustomFeignRequestLogging customFeignRequestLogging() {
        return new CustomFeignRequestLogging();
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.BASIC;
    }
}

Run Code Online (Sandbox Code Playgroud)

  • 这是一个非常有用的答案。我只是想澄清在需要编写回复时需要小心的部分。重建响应将如下所示: `ByteArray bodyData = Util.toByteArray(response.body().asInputStream())` `Response responseCopy = response.toBuilder().body(bodyData).build()` 这样,您就可以可以根据需要继续使用“responseCopy”。 (2认同)

mna*_*dev 5

接受的答案对我不起作用,直到我将以下设置添加到我的 application.yml 文件中:

logging:
  level:
    com:
      mypackage1:
        mysubackage1:
          mysubpackage2: DEBUG
Run Code Online (Sandbox Code Playgroud)