前言
在项目开发过程中经常需要使用http协议请求第三方接口,而所有针对第三方的请求都强烈推荐打印请求日志,以便问题追踪。最常见的做法是封装一个http请求的工具类,在里面定制一些日志打印,但这种做法真的比较low,本文将分享一下在spring boot中如何优雅的打印http请求日志。
一、spring-rest-template-logger实战
1、引入依赖
<dependency> <groupid>org.hobsoft.spring</groupid> <artifactid>spring-rest-template-logger</artifactid> <version>2.0.0</version> </dependency>
2、配置resttemplate
@configuration public class resttemplateconfig { @bean public resttemplate resttemplate() { resttemplate resttemplate = new resttemplatebuilder() .customizers(new loggingcustomizer()) .build(); return resttemplate; } }
3、配置resttemplate请求的日志级别
logging.level.org.hobsoft.spring.resttemplatelogger.loggingcustomizer = debug
4、单元测试
@springboottest @slf4j class limitapplicationtests { @resource resttemplate resttemplate; @test void testhttplog() throws exception{ string requesturl = "https://api.uomg.com/api/icp"; //构建json请求参数 jsonobject params = new jsonobject(); params.put("domain", "www.baidu.com"); //请求头声明请求格式为json httpheaders headers = new httpheaders(); headers.setcontenttype(mediatype.application_json); //创建请求实体 httpentity<string> entity = new httpentity<>(params.tostring(), headers); //执行post请求,并响应返回字符串 string restext = resttemplate.postforobject(requesturl, entity, string.class); system.out.println(restext); } }
5、日志打印
2023-06-25 10:43:44.780 debug [sleuth,b6ac76a169b1af33,b6ac76a169b1af33] 63501 --- [ main] o.h.s.r.loggingcustomizer : request: post https://api.uomg.com/api/icp {"domain":"www.baidu.com"}
2023-06-25 10:43:45.849 debug [sleuth,b6ac76a169b1af33,b6ac76a169b1af33] 63501 --- [ main] o.h.s.r.loggingcustomizer : response: 200 {"code":200901,"msg":"查询域名不能为空"}
{"code":200901,"msg":"查询域名不能为空"}
可以看见,我们只是简单的向resttemplate中配置了loggingcustomizer,就实现了http请求的日志通用化打印,在request和response中分别打印出了请求的入参和响应结果。
6、自定义日志打印格式
可以通过继承logformatter接口实现自定义的日志打印格式。
resttemplate resttemplate = new resttemplatebuilder() .customizers(new loggingcustomizer(logfactory.getlog(loggingcustomizer.class), new mylogformatter())) .build();
默认的日志打印格式化类defaultlogformatter:
public class defaultlogformatter implements logformatter { private static final charset default_charset; public defaultlogformatter() { } //格式化请求 public string formatrequest(httprequest request, byte[] body) { string formattedbody = this.formatbody(body, this.getcharset(request)); return string.format("request: %s %s %s", request.getmethod(), request.geturi(), formattedbody); } //格式化响应 public string formatresponse(clienthttpresponse response) throws ioexception { string formattedbody = this.formatbody(streamutils.copytobytearray(response.getbody()), this.getcharset(response)); return string.format("response: %s %s", response.getstatuscode().value(), formattedbody); } …… }
可以参考defaultlogformatter的实现,定制自定的日志打印格式化类mylogformatter。
二、原理分析
首先分析下loggingcustomizer类,通过查看源码发现,loggingcustomizer继承自resttemplatecustomizer,resttemplatecustomizer表示resttemplate的定制器,resttemplatecustomizer是一个函数接口,只有一个方法customize,用来扩展定制resttemplate的属性。
@functionalinterface public interface resttemplatecustomizer { void customize(resttemplate resttemplate); }
loggingcustomizer的核心方法customize:
public class loggingcustomizer implements resttemplatecustomizer{ public void customize(resttemplate resttemplate) { resttemplate.setrequestfactory(new bufferingclienthttprequestfactory(resttemplate.getrequestfactory())); //向resttemplate中注入了日志拦截器 resttemplate.getinterceptors().add(new logginginterceptor(this.log, this.formatter)); } }
日志拦截器中的核心方法:
public class logginginterceptor implements clienthttprequestinterceptor { private final log log; private final logformatter formatter; public logginginterceptor(log log, logformatter formatter) { this.log = log; this.formatter = formatter; } public clienthttpresponse intercept(httprequest request, byte[] body, clienthttprequestexecution execution) throws ioexception { if (this.log.isdebugenabled()) { //打印http请求的入参 this.log.debug(this.formatter.formatrequest(request, body)); } clienthttpresponse response = execution.execute(request, body); if (this.log.isdebugenabled()) { //打印http请求的响应结果 this.log.debug(this.formatter.formatresponse(response)); } return response; } }
原理小结:
通过向resttemplate对象中添加自定义的日志拦截器logginginterceptor,使用自定义的格式化类defaultlogformatter来打印http请求的日志。
三、优化改进
可以借鉴spring-rest-template-logger的实现,通过spring boot start自动化配置原理, 声明自动化配置类resttemplateautoconfiguration,自动配置resttemplate。
这里只是提供一些思路,搞清楚相关组件的原理后,我们就可以轻松定制通用的日志打印组件。
@configuration public class resttemplateautoconfiguration { @bean @conditionalonmissingbean public resttemplate resttemplate() { resttemplate resttemplate = new resttemplatebuilder() .customizers(new loggingcustomizer()) .build(); return resttemplate; } }
总结
这里的优雅打印并不是针对http请求日志打印的格式,而是通过向resttemplate中注入拦截器实现通用性强、代码侵入性小、具有可定制性的日志打印方式。
在spring boot中http请求都推荐采用resttemplate模板类
,而无需自定义http请求的静态工具类,比如httputil- 推荐在配置类中采用@bean将resttemplate类配置成统一通用的单例对象注入到spring 容器中,而不是每次使用的时候重新声明。
- 推荐采用拦截器实现http请求日志的通用化打印
到此这篇关于springboot中如何打印http请求日志的文章就介绍到这了,更多相关springboot打印http请求日志内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论