openfeign开启日志

发布时间 2023-04-01 16:27:25作者: shigp1

openfeign的日志级别有:

  1. NONE:默认,不开启日志
  2. BASIC:只记录请求方法和URL以及响应状态代码和执行时间
  3. HEADERS:记录基本信息以及请求和响应标头。
  4. FULL:记录请求和响应的标题、正文和元数据。

 
 

全局日志

加入Logger.Level Bean:

@Configuration
public class MyConfigration {

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

访问http://localhost:8003/helloByFeign,还是没看到日志,还需要改变SpringBoot的日志级别,在application.properties加入:

logging.level.com.example.feign=debug

com.example.feign是feign所在的包。

重新访问http://localhost:8003/helloByFeign:

 
 

还可以在application.properties加入

feign.client.config.default.loggerLevel=FULL

开启openfeign的全局日志级别。

 

单个feign的日志级别

新建UserProvider模块,引入

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

并设置parent为:

<parent>
    <groupId>com.springCloudDemo</groupId>
    <artifactId>SpringCloudDemo</artifactId>
    <version>1.0.1-SNAPSHOT</version>
</parent>

在application.properties增加配置:

server.port=8004

spring.application.name=userProvider

eureka.client.service-url.defaultZone=http://user:123@localhost:8761/eureka/

并增加controller:

@RestController
public class UserController {

    @RequestMapping("/getUser")
    public Map<String, Object>  getUser() {
        Map<String, Object> map = new HashMap<>();
        map.put("name","李四");
        map.put("age",30);
        return map;
    }
}

在ConsumerByRibbon新建userFeign包,增加feign调用:

@FeignClient(value = "userProvider")
public interface UserFeign {

     @RequestMapping("/getUser")
     Map<String, Object> getUser();
}

在application.properties加入:

logging.level.com.example.userFeign=debug

并在controller增加:

@Autowired
UserFeign userFeign;

@RequestMapping("/getUser")
public Map<String, Object> getUser() {
    return userFeign.getUser();
}

 
 

修改HelloFeign:

@FeignClient(value = "producer",configuration = HelloConfigration.class)
public interface HelloFeign {
    @RequestMapping("/hello")
    public String hello(@RequestParam String name);
}

@Configuration
public class HelloConfigration {

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

注意HelloConfigration类不要放在SpringBoot的包扫描路径下。

注释掉全局日志配置,访问http://localhost:8003/helloByFeign,看到:

 
在访问http://localhost:8003/getUser,可以见到没有日志输出。HelloFeign可以打印日志,UserFeign不能打印日志。

 
 

还可以在application.properties加入:

feign.client.config.producer.loggerLevel=FULL

producer是feign要调用的服务名。
 
去除HelloFeign类上的configuration属性,访问http://localhost:8003/helloByFeign和http://localhost:8003/getUser,看到HelloFeign可以打印日志,UserFeign不能打印日志。