1. 技术选项:logbook
2. 使用方法
a. 导入logbook的maven依赖
<logbook.version>1.3.0</logbook.version>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-core</artifactId>
<version>${logbook.version}</version>
</dependency>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-servlet</artifactId>
<version>${logbook.version}</version>
</dependency>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-httpclient</artifactId>
<version>${logbook.version}</version>
</dependency>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-spring-boot-starter</artifactId>
<version>${logbook.version}</version>
</dependency>
b. 在application.properties中配置显示方式
# 自动打印HTTP/HTTPCLIENT日志
logbook.write.level=info
logbook.format.style=curl # 或http
c. 在定义httpClient的bean中,加入拦截
@Autowired
private LogbookHttpRequestInterceptor logbookHttpRequestInterceptor;
@Autowired
private LogbookHttpResponseInterceptor logbookHttpResponseInterceptor;
@Bean
@ConditionalOnMissingBean(HttpClient.class)
public HttpClient httpClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(properties.getConnectTimeOut())
.setSocketTimeout(properties.getSocketTimeOut())
.build();//构建requestConfig
HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
.setUserAgent(properties.getAgent())
.setMaxConnPerRoute(properties.getMaxConnPerRoute())
.setMaxConnTotal(properties.getMaxConnTotal())
//使用logbook打印HTTP请求的日志
.addInterceptorFirst(logbookHttpRequestInterceptor)
.addInterceptorFirst(logbookHttpResponseInterceptor)
//使用长连接
//.setConnectionReuseStrategy(new NoConnectionReuseStrategy())
.build();
return client;
}
此时项目发送http请求,就会以curl/http的方式,显示调用的http url日志。