有没有办法记录假装客户的响应时间

时间:2019-05-15 01:51:20

标签: spring-boot metrics spring-cloud-feign actuator openfeign

@FeignClient(...)
public interface SomeClient {
@RequestMapping(value = "/someUrl", method = POST, consumes = "application/json")
    ResponseEntity<String> createItem(...);

}

是否可以找到createItem api调用的响应时间? 我们正在使用弹簧靴,执行器,普罗米修斯。

3 个答案:

答案 0 :(得分:2)

我们提供了一种简单的方法以及一种定制的方式来记录伪装客户的请求和响应(包括响应时间)。我们必须注入feign.Logger.Level bean,就是这样。

  1. 默认/直接转发方式
@Bean
Logger.Level feignLoggerLevel() {
  return Logger.Level.BASIC;
}

有BASIC,FULL,HEADERS,NONE(默认)日志记录级别可用for more details

上面的bean注入将以以下格式记录假请求和响应:

请求

refer

log(configKey, "---> %s %s HTTP/1.1", request.httpMethod().name(), request.url());

ex:2019-09-26 12:50:12.163 [DEBUG] [http-nio-4200-exec-5] [com.sample.FeignClient:72] [FeignClient#getUser] ---> END HTTP (0-byte body)

其中configkey的意思是FeignClientClassName#FeignClientCallingMethodName的{​​{1}}。

响应

refer

ApiClient#apiMethod

log(configKey, "<--- HTTP/1.1 %s%s (%sms)", status, reason, elapsedTime); ex:2019-09-26 12:50:12.163 [DEBUG] [http-nio-4200-exec-5] [com.sample.FeignClient:72] [FeignClient#getUser] <--- HTTP/1.1 200 OK (341ms) 是API调用所花费的响应时间。

注意:如果您希望使用伪装客户端日志记录的默认方式,则我们还必须考虑底层应用程序的日志记录级别,因为elapsedTime类记录了伪装请求和响应feign.Slf4jLogger级(refer)的详细信息。如果基础日志记录级别高于DEBUG,则可能需要为DEBUG日志记录程序包/类指定显式记录器,否则它将无法正常工作。

  1. 自定义方式   如果您希望使用自定义格式的日志记录,则可以扩展feign类并自定义日志记录。对于一个典型的示例,如果我想将请求和响应的标头详细信息作为列表记录在一行中(默认情况下,Logger.Level.HEADERS多行打印该标头):
feign.Logger

我们还必须注入customFeignLogger类bean

package com.test.logging.feign;

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 customFeignLogger 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) %s", request.httpMethod().name(), request.url(), bodyLength, request.headers());
        }
    }

    @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) %s", request.httpMethod().name(), request.url(), status, elapsedTime, response.headers());
        }
        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);
    }
}

如果您要自己构建FeignClient,则可以使用自定义的记录器进行构建:

  @Bean
    public customFeignLogger customFeignLogging() {
        return new customFeignLogger();
    }

答案 1 :(得分:0)

在项目中添加以下注释。

package com.example.annotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DebugTracking {
    @Aspect
    @Component
    public static class DebugTrackingAspect {
        @Around("@annotation(com.example.annotation.DebugTracking)")
        public Object trackExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start(joinPoint.toShortString());

            Exception exceptionThrown = null;

            try {
                // Execute the joint point as usual
                return joinPoint.proceed();

            } catch (Exception ex) {
                exceptionThrown = ex;
                throw ex;

            } finally {
                stopWatch.stop();

                System.out.println(String.format("%s took %dms.", stopWatch.getLastTaskName(), stopWatch.getLastTaskTimeMillis()));

                if (exceptionThrown != null) {
                    System.out.println(String.format("Exception thrown: %s", exceptionThrown.getMessage()));
                    exceptionThrown.printStackTrace();

                }
            }
        }
    }
}

然后用@FeignClient注释要在@DebugTracking中跟踪的方法。

答案 2 :(得分:0)

我正在使用以下内容(使用 Spring 和 Lombok):

@Configuration // from Spring
@Slf4j // from Lombok
public class MyFeignConfiguration {
    @Bean // from Spring
    public MyFeignClient myFeignClient() {
        return Feign.builder()
            .logger(new Logger() {
                @Override
                protected void log(String configKey, String format, Object... args) {
                    LOG.info( String.format(methodTag(configKey) + format, args)); // LOG is the Lombok Slf4j object
                }
            })
            .logLevel(Logger.Level.BASIC) // see https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html#_feign_logging
            .target(MyFeignClient.class,"http://localhost:8080");
    }
}
相关问题