写了个牛逼的日志切面,甩锅更方便了
最近项目进入联调阶段,服务层的接口需要和协议层进行交互,协议层需要将入参〔json字符串〕组装成服务层所需的json字符串,组装的过程中很容易出错。
入参出错导致接口调试失败问题在联调中出现很多次,因此就想写一个请求日志切面把入参信息打印一下,同时协议层调用服务层接口名称对不上也出现了几次,通过请求日志切面就可以知道上层是否有没有发起调用,方便前后端甩锅还能拿出证据。
写在前面
本篇文章是实战性的,对于切面的原理不会讲解,只会简单介绍一下切面的知识点
切面介绍
面向切面编程是一种编程范式,它作为OOP面向对象编程的一种补充,用于处理系统中分布于各个模块的横切关注点,比如事务管理、权限控制、缓存控制、日志打印等等。
AOP把软件的功能模块分为两个部分:核心关注点和横切关注点。业务处理的主要功能为核心关注点,而非核心、需要拓展的功能为横切关注点。AOP的作用在于分离系统中的各种关注点,将核心关注点和横切关注点进行分离,使用切面有以下好处:集中处理某一关注点横切逻辑可以很方便的添加删除关注点侵入性少,增强代码可读性及可维护性因此当想打印请求日志时很容易想到切面,对控制层代码0侵入切面的使用【基于注解】Aspect声明该类为一个注解类
切点注解:Pointcut定义一个切点,可以简化代码
通知注解:Before在切点之前执行代码After在切点之后执行代码AfterReturning切点返回内容后执行代码,可以对切点的返回值进行封装AfterThrowing切点抛出异常后执行Around环绕,在切点前后执行代码动手写一个请求日志切面使用Pointcut定义切点Pointcut(execution(yourpackage。controller。。(。。)))publicvoidrequestServer(){}
Pointcut定义了一个切点,因为是请求日志切边,因此切点定义的是Controller包下的所有类下的方法。定义切点以后在通知注解中直接使用requestServer方法名就可以了使用Before再切点前执行Before(requestServer())publicvoiddoBefore(JoinPointjoinPoint){ServletRequestAttributesattributes(ServletRequestAttributes)RequestContextHolder。getRequestAttributes();HttpServletRequestrequestattributes。getRequest();LOGGER。info(Start);LOGGER。info(IP:{},request。getRemoteAddr());LOGGER。info(URL:{},request。getRequestURL()。toString());LOGGER。info(HTTPMethod:{},request。getMethod());LOGGER。info(ClassMethod:{}。{},joinPoint。getSignature()。getDeclaringTypeName(),joinPoint。getSignature()。getName());}
在进入Controller方法前,打印出调用方IP、请求URL、HTTP请求类型、调用的方法名使用Around打印进入控制层的入参Around(requestServer())publicObjectdoAround(ProceedingJoinPointproceedingJoinPoint)throwsThrowable{longstartSystem。currentTimeMillis();ObjectresultproceedingJoinPoint。proceed();LOGGER。info(RequestParams:{},getRequestParams(proceedingJoinPoint));LOGGER。info(Result:{},result);LOGGER。info(TimeCost:{}ms,System。currentTimeMillis()start);returnresult;}
打印了入参、结果以及耗时getRquestParams方法privateMapString,ObjectgetRequestParams(ProceedingJoinPointproceedingJoinPoint){MapString,ObjectrequestParamsnewHashMap();参数名String〔〕paramNames((MethodSignature)proceedingJoinPoint。getSignature())。getParameterNames();参数值Object〔〕paramValuesproceedingJoinPoint。getArgs();for(inti0;iparamNames。length;i){ObjectvalueparamValues〔i〕;如果是文件对象if(valueinstanceofMultipartFile){MultipartFilefile(MultipartFile)value;valuefile。getOriginalFilename();获取文件名}requestParams。put(paramNames〔i〕,value);}returnrequestParams;}
通过PathVariable以及RequestParam注解传递的参数无法打印出参数名,因此需要手动拼接一下参数名,同时对文件对象进行了特殊处理,只需获取文件名即可After方法调用后执行After(requestServer())publicvoiddoAfter(JoinPointjoinPoint){LOGGER。info(End);}
没有业务逻辑只是打印了End完整切面代码ComponentAspectpublicclassRequestLogAspect{privatefinalstaticLoggerLOGGERLoggerFactory。getLogger(RequestLogAspect。class);Pointcut(execution(yourpackage。controller。。(。。)))publicvoidrequestServer(){}Before(requestServer())publicvoiddoBefore(JoinPointjoinPoint){ServletRequestAttributesattributes(ServletRequestAttributes)RequestContextHolder。getRequestAttributes();HttpServletRequestrequestattributes。getRequest();LOGGER。info(Start);LOGGER。info(IP:{},request。getRemoteAddr());LOGGER。info(URL:{},request。getRequestURL()。toString());LOGGER。info(HTTPMethod:{},request。getMethod());LOGGER。info(ClassMethod:{}。{},joinPoint。getSignature()。getDeclaringTypeName(),joinPoint。getSignature()。getName());}Around(requestServer())publicObjectdoAround(ProceedingJoinPointproceedingJoinPoint)throwsThrowable{longstartSystem。currentTimeMillis();ObjectresultproceedingJoinPoint。proceed();LOGGER。info(RequestParams:{},getRequestParams(proceedingJoinPoint));LOGGER。info(Result:{},result);LOGGER。info(TimeCost:{}ms,System。currentTimeMillis()start);returnresult;}After(requestServer())publicvoiddoAfter(JoinPointjoinPoint){LOGGER。info(End);}获取入参paramproceedingJoinPointreturnprivateMapString,ObjectgetRequestParams(ProceedingJoinPointproceedingJoinPoint){MapString,ObjectrequestParamsnewHashMap();参数名String〔〕paramNames((MethodSignature)proceedingJoinPoint。getSignature())。getParameterNames();参数值Object〔〕paramValuesproceedingJoinPoint。getArgs();for(inti0;iparamNames。length;i){ObjectvalueparamValues〔i〕;如果是文件对象if(valueinstanceofMultipartFile){MultipartFilefile(MultipartFile)value;valuefile。getOriginalFilename();获取文件名}requestParams。put(paramNames〔i〕,value);}returnrequestParams;}}高并发下请求日志切面
写完以后对自己的代码很满意,但是想着可能还有完善的地方就和朋友交流了一下。emmmm
果然还有继续优化的地方每个信息都打印一行,在高并发请求下确实会出现请求之间打印日志串行的问题,因为测试阶段请求数量较少没有出现串行的情况,果然生产环境才是第一发展力,能够遇到更多bug,写更健壮的代码解决日志串行的问题只要将多行打印信息合并为一行就可以了,因此构造一个对象RequestInfo。javaDatapublicclassRequestInfo{privateStringip;privateStringurl;privateStringhttpMethod;privateStringclassMethod;privateObjectrequestParams;privateObjectresult;privateLongtimeCost;}环绕通知方法体Around(requestServer())publicObjectdoAround(ProceedingJoinPointproceedingJoinPoint)throwsThrowable{longstartSystem。currentTimeMillis();ServletRequestAttributesattributes(ServletRequestAttributes)RequestContextHolder。getRequestAttributes();HttpServletRequestrequestattributes。getRequest();ObjectresultproceedingJoinPoint。proceed();RequestInforequestInfonewRequestInfo();requestInfo。setIp(request。getRemoteAddr());requestInfo。setUrl(request。getRequestURL()。toString());requestInfo。setHttpMethod(request。getMethod());requestInfo。setClassMethod(String。format(s。s,proceedingJoinPoint。getSignature()。getDeclaringTypeName(),proceedingJoinPoint。getSignature()。getName()));requestInfo。setRequestParams(getRequestParamsByProceedingJoinPoint(proceedingJoinPoint));requestInfo。setResult(result);requestInfo。setTimeCost(System。currentTimeMillis()start);LOGGER。info(RequestInfo:{},JSON。toJSONString(requestInfo));returnresult;}
将url、httprequest这些信息组装成RequestInfo对象,再序列化打印对象
打印序列化对象结果而不是直接打印对象是因为序列化有更直观、更清晰,同时可以借助在线解析工具对结果进行解析
是不是还不错
在解决高并发下请求串行问题的同时添加了对异常请求信息的打印,通过使用AfterThrowing注解对抛出异常的方法进行处理RequestErrorInfo。javaDatapublicclassRequestErrorInfo{privateStringip;privateStringurl;privateStringhttpMethod;privateStringclassMethod;privateObjectrequestParams;privateRuntimeExceptionexception;}异常通知环绕体AfterThrowing(pointcutrequestServer(),throwinge)publicvoiddoAfterThrow(JoinPointjoinPoint,RuntimeExceptione){ServletRequestAttributesattributes(ServletRequestAttributes)RequestContextHolder。getRequestAttributes();HttpServletRequestrequestattributes。getRequest();RequestErrorInforequestErrorInfonewRequestErrorInfo();requestErrorInfo。setIp(request。getRemoteAddr());requestErrorInfo。setUrl(request。getRequestURL()。toString());requestErrorInfo。setHttpMethod(request。getMethod());requestErrorInfo。setClassMethod(String。format(s。s,joinPoint。getSignature()。getDeclaringTypeName(),joinPoint。getSignature()。getName()));requestErrorInfo。setRequestParams(getRequestParamsByJoinPoint(joinPoint));requestErrorInfo。setException(e);LOGGER。info(ErrorRequestInfo:{},JSON。toJSONString(requestErrorInfo));}
对于异常,耗时是没有意义的,因此不统计耗时,而是添加了异常的打印
最后放一下完整日志请求切面代码:ComponentAspectpublicclassRequestLogAspect{privatefinalstaticLoggerLOGGERLoggerFactory。getLogger(RequestLogAspect。class);Pointcut(execution(yourpackage。controller。。(。。)))publicvoidrequestServer(){}Around(requestServer())publicObjectdoAround(ProceedingJoinPointproceedingJoinPoint)throwsThrowable{longstartSystem。currentTimeMillis();ServletRequestAttributesattributes(ServletRequestAttributes)RequestContextHolder。getRequestAttributes();HttpServletRequestrequestattributes。getRequest();ObjectresultproceedingJoinPoint。proceed();RequestInforequestInfonewRequestInfo();requestInfo。setIp(request。getRemoteAddr());requestInfo。setUrl(request。getRequestURL()。toString());requestInfo。setHttpMethod(request。getMethod());requestInfo。setClassMethod(String。format(s。s,proceedingJoinPoint。getSignature()。getDeclaringTypeName(),proceedingJoinPoint。getSignature()。getName()));requestInfo。setRequestParams(getRequestParamsByProceedingJoinPoint(proceedingJoinPoint));requestInfo。setResult(result);requestInfo。setTimeCost(System。currentTimeMillis()start);LOGGER。info(RequestInfo:{},JSON。toJSONString(requestInfo));returnresult;}AfterThrowing(pointcutrequestServer(),throwinge)publicvoiddoAfterThrow(JoinPointjoinPoint,RuntimeExceptione){ServletRequestAttributesattributes(ServletRequestAttributes)RequestContextHolder。getRequestAttributes();HttpServletRequestrequestattributes。getRequest();RequestErrorInforequestErrorInfonewRequestErrorInfo();requestErrorInfo。setIp(request。getRemoteAddr());requestErrorInfo。setUrl(request。getRequestURL()。toString());requestErrorInfo。setHttpMethod(request。getMethod());requestErrorInfo。setClassMethod(String。format(s。s,joinPoint。getSignature()。getDeclaringTypeName(),joinPoint。getSignature()。getName()));requestErrorInfo。setRequestParams(getRequestParamsByJoinPoint(joinPoint));requestErrorInfo。setException(e);LOGGER。info(ErrorRequestInfo:{},JSON。toJSONString(requestErrorInfo));}获取入参paramproceedingJoinPointreturnprivateMapString,ObjectgetRequestParamsByProceedingJoinPoint(ProceedingJoinPointproceedingJoinPoint){参数名String〔〕paramNames((MethodSignature)proceedingJoinPoint。getSignature())。getParameterNames();参数值Object〔〕paramValuesproceedingJoinPoint。getArgs();returnbuildRequestParam(paramNames,paramValues);}privateMapString,ObjectgetRequestParamsByJoinPoint(JoinPointjoinPoint){参数名String〔〕paramNames((MethodSignature)joinPoint。getSignature())。getParameterNames();参数值Object〔〕paramValuesjoinPoint。getArgs();returnbuildRequestParam(paramNames,paramValues);}privateMapString,ObjectbuildRequestParam(String〔〕paramNames,Object〔〕paramValues){MapString,ObjectrequestParamsnewHashMap();for(inti0;iparamNames。length;i){ObjectvalueparamValues〔i〕;如果是文件对象if(valueinstanceofMultipartFile){MultipartFilefile(MultipartFile)value;valuefile。getOriginalFilename();获取文件名}requestParams。put(paramNames〔i〕,value);}returnrequestParams;}DatapublicclassRequestInfo{privateStringip;privateStringurl;privateStringhttpMethod;privateStringclassMethod;privateObjectrequestParams;privateObjectresult;privateLongtimeCost;}DatapublicclassRequestErrorInfo{privateStringip;privateStringurl;privateStringhttpMethod;privateStringclassMethod;privateObjectrequestParams;privateRuntimeExceptionexception;}}
赶紧给你们的应用加上吧【如果没加的话】,没有日志的话,总怀疑上层出错,但是却拿不出证据
关于traceId跟踪定位,可以根据traceId跟踪整条调用链,以log4j2为例介绍如何加入traceId添加拦截器publicclassLogInterceptorimplementsHandlerInterceptor{privatefinalstaticStringTRACEIDtraceId;OverridepublicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{StringtraceIdjava。util。UUID。randomUUID()。toString()。replaceAll(,)。toUpperCase();ThreadContext。put(traceId,traceId);returntrue;}OverridepublicvoidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,ModelAndViewmodelAndView)throwsException{}OverridepublicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex)throwsException{ThreadContext。remove(TRACEID);}}
在调用前通过ThreadContext加入traceId,调用完成后移除修改日志配置文件在原来的日志格式中
添加traceId的占位符property〔TRACEID:X{traceId}〕d{HH:mm:ss。SSS}5levelclass{1}。M()LmsgxExnproperty执行效果
日志跟踪更方便
DMC是配置logback和log4j使用的,使用方式和ThreadContext差不多,将ThreadContext。put替换为MDC。put即可,同时修改日志配置文件。
log4j2也是可以配合MDC一起使用的
MDC是slf4j包下的,其具体使用哪个日志框架与我们的依赖有关。
欧洲进口的平价洗碗机是什么水平?Arda13套洗碗机体验都说洗碗机是国内厨电的新领域,但它在欧美国家已经流行了几十年。仅在2012年,德国和美国75的家庭都有洗碗机。一款家电产品,生命周期可以达到几十年,只能用它是很多人的刚需……
平板做logo前两天小哥iPad买完之后,本人大方地给他用家庭共享了一众绘图设计软件,同时抖音分享了好几个画手教学视频,果不其然,接下来的操作让我大跌眼镜。最佳观影神器其实iPa……
还在为加班做任务而苦恼?上百种资源免费送!只需要这么做这个时代为科技时代,是计算机应用时代,目前,任何上班职员都少不了要做PPT等一系列课件,做课件加班到十点的朋友那是很常见的,自然这些朋友也会感到很困扰。今天小编就给大家推……
上汽越野扛把子,底气不输陆巡,2。0T柴油有500扭矩相信大多数的男性消费者都有一个越野梦吧,但大多数人可能是因为资金问题或是顾及家庭的原因,一直没有机会去实现这个梦想。今天小编就给大家推荐一款车,它既有着过硬的越野能力,也可以完……
2019最新离职补偿金计算公式一览表为了保护劳动者的正当权益,《中华人民共和国劳动法》、《中华人民共和国劳动合同法》以及其他的法律法规对员工的离职补偿金进行了相关的规定,汇总如下表。《员工离职补偿汇总表》……
家里有点丑的电表箱,该怎么拯救你家墙面有没有被又丑又大的电表箱占据过?它不能随意拆除,在装修精美的空间里,强硬的占据走廊、玄关或者餐厅墙面最中心的位置,降低了整个空间的美感,甚至影响了居住的心情。……
42dB混合主动降噪!HAKIITIMEPRO前言作为一名出街必带耳机的用户来说,我们都很追求耳机的降噪功能。20多dB的降噪体验可能不太够用,40多dB可能会更符合城市通勤且深度依赖降噪的用户。而更高dB的降噪可能……
不必忍受冷风直吹,云米SpaceE全域风空调使用体验大家好,我是南北桃源没想到一转眼就已经是夏天了,客厅的空调还是老式的立式空调,已经用了很多年,虽然一直没坏,但制冷制热效果差,耗电量大,冷风直吹非常难受,家里的老人一直想……
旗舰级镜头模组麒麟820,荣耀30S带来革命性拍照体验3月25日,荣耀手机发布荣耀30S的最新预热海报,透露其在新一代麒麟8205GSoC芯片加持下,能够用‘芯’记录世界,让世界更加清晰。荣耀总裁赵明也表示,影像能力一直是荣耀深耕……
粉色沙滩逐浪追龙,太平洋深处的神奇秘境朋友一家想去海边,咨询我,想要人少小众、又在海边、冬天也能下海,风景美还不用搞签证的地方。我想了下,回答说,那就科莫多吧位于南半球的小岛,价格巴适,不需要签证,旅游服务业……
域名实名为什么老是审核不通过?【新网域名科普】域名是互联网上的具有唯一性的标识,每一个域名的注册都是独一无二、不可重复的。域名实名制迫使企业或个人对网站发布的内容负责,到时如果产生纠纷,也可有据可查,这有利……
华为MateBook142021款实测,智慧办公再进一步华为MateBook142021款近期正式发布,凭借全新第11代英特尔酷睿处理器、高清2K触控屏、超高屏占比、WiFi6、全金属机身设计,这款华为旗下全新的笔记本电脑已经足以称……