SPRINGBOOT-23-ASPECTJ log records and threadlocal memory leaks

Source: Internet
Author: User
Tags throwable

For processing and responding to request parameters, it can be tedious to manifest the log in code, and a common solution is to use the spring cut-off scheme.

Here is the cut of Springboot: http://www.cnblogs.com/wenbronk/p/6848984.html

At the beginning of the ASPECTJ cut-off solution:
Package Com.iwhere.easy.travel.aspect;import Java.sql.date;import java.text.simpledateformat;import Java.util.enumeration;import Java.util.uuid;import Javax.servlet.http.httpservletrequest;import Org.aspectj.lang.joinpoint;import Org.aspectj.lang.annotation.afterreturning;import Org.aspectj.lang.annotation.afterthrowing;import Org.aspectj.lang.annotation.aspect;import Org.aspectj.lang.annotation.before;import Org.aspectj.lang.annotation.pointcut;import Org.slf4j.Logger;import Org.slf4j.loggerfactory;import Org.springframework.stereotype.component;import Org.springframework.web.context.request.requestcontextholder;import Org.springframework.web.context.request.servletrequestattributes;import com.alibaba.fastjson.jsonobject;@ Aspect@component Public classControlleraspect {protectedFinal Logger Logger = Loggerfactory.getlogger ( This. GetClass ()); PrivateString name ="Easy-travel-server"; @Pointcut ("Execution (Public * com.wenbronk.controller.*.* (..))")     Public voidControllerlog () {} @Pointcut ("Execution (Public * com.wenbronk.service.*.* (..))")     Public voidServicelog () {}PrivateThreadlocal<long> StartTime =NewThreadlocal<>(); PrivateThreadlocal<string> RequestID =NewThreadlocal<>(); PrivateThreadlocal<string> InterfaceName =NewThreadlocal<>(); Privatethreadlocal<string> param =NewThreadlocal<>(); PrivateSimpleDateFormat DataFormat =NewSimpleDateFormat ("yyyy-mm-dd ' T ' HH:mm:ss. SSS"); @Before ("Controllerlog ()")     Public voidDobefore (Joinpoint joinpoint) throws Throwable {//receive request, log request contentServletrequestattributes attributes =(servletrequestattributes) requestcontextholder.getrequestattributes (); HttpServletRequest Request=attributes.getrequest (); //Set Request Start timeStartTime.Set(System.currenttimemillis ()); Date sttimedate=NewDate (StartTime.Get()); String Datestr=Dataformat.format (sttimedate); //set the request identityString Requestidstr =Uuid.randomuuid (). toString (); RequestID.Set(REQUESTIDSTR); //Extract all Parameters ParamjsonEnumeration<string> Paramnames =Request.getparameternames (); Jsonobject Paramjson=NewJsonobject ();  while(Paramnames.hasmoreelements ()) {String paramname=paramnames.nextelement ();        Paramjson.put (ParamName, Request.getparameter (paramname)); }                //Extract Interface ID (intercepted in URL)String Requesturl =Request.getrequesturl (). toString (); intStart = Requesturl.lastindexof ("/")+1; String Interfacenamestr=NULL; if(Requesturl.contains ("?") ) {Interfacenamestr= Requesturl.substring (Start, Requesturl.indexof ("?")); } Else{interfacenamestr=requesturl.substring (start); } param.Set(Paramjson.tojsonstring ()); InterfaceName.Set(INTERFACENAMESTR); //Place the unique identity of the requst in the request, which can be worn in other parts .Request.setattribute ("RequestID", RequestID.Get()); } @AfterReturning (Returning="rvt", pointcut="Controllerlog ()")     Public voiddoafterreturning (Joinpoint joinpoint,object rvt) throws Throwable {//receive request, log request contentServletrequestattributes attributes =(servletrequestattributes) requestcontextholder.getrequestattributes (); HttpServletRequest Request=attributes.getrequest (); Logger.info ("finished"+" "+ name +" "+ InterfaceName.Get() +" "+ RequestID.Get() +" "+ Request.getrequesturl (). toString () +" "+ param.Get()                 + (System.currenttimemillis ()-StartTime.Get())                 +" "+rvt.tostring ()); } @AfterThrowing (Throwing="ex", pointcut="Controllerlog ()")     Public voiddoafterthrowing (Joinpoint joinpoint, Throwable ex) throws Throwable {//receive request, log request contentServletrequestattributes attributes =(servletrequestattributes) requestcontextholder.getrequestattributes (); HttpServletRequest Request=attributes.getrequest (); //where it happened         intLineNum =0; String ClassName=NULL; String MethodName=NULL; Stacktraceelement[] St=Ex.getstacktrace ();  for(stacktraceelement stacktraceelement:st) {linenum=Stacktraceelement.getlinenumber (); ClassName=Stacktraceelement.getclassname (); MethodName=Stacktraceelement.getmethodname (); System. out. println ("[Class:"+ ClassName +"] Call"+ MethodName +"when the first"+LineNum+"An exception occurred at the line code! Exception Type:"+Ex.getclass (). GetName ());  Break; } String exceptionmessage="[Class:"+ ClassName +"] Call"+ MethodName +"when the first"+ LineNum +"An exception occurred at the line code! Exception Type:"+Ex.getclass (). GetName (); Logger.info ("Exception"+" "+ name +" "+ InterfaceName.Get() +" "+ RequestID.Get() +" "+ Request.getrequesturl (). toString () +" "+ param.Get()                 +" "+exceptionmessage); }}

There is a before and after in this, and then there is an exception handling method

Occasionally see this blog

http://blog.csdn.net/lhqj1992/article/details/52451136https://my.oschina.net/ xpbug/blog/113444https://segmentfault.com/a/1190000000537475

Since this project employs a thread pool, it is possible that memory has been rising and has reached a stable state after the thread pool max, and there has been a memory leak we think of

Then change to this method:

Package Com.iwhere.scrapy.aspect;import Javax.servlet.http.httpservletrequest;import Org.aspectj.lang.proceedingjoinpoint;import Org.aspectj.lang.annotation.around;import Org.aspectj.lang.annotation.aspect;import Org.aspectj.lang.annotation.pointcut;import Org.slf4j.Logger;import Org.slf4j.loggerfactory;import Org.springframework.context.annotation.configuration;import Org.springframework.web.context.request.requestattributes;import Org.springframework.web.context.request.requestcontextholder;import Org.springframework.web.context.request.servletrequestattributes;import Com.alibaba.fastjson.JSON;/** * Log Slice class * @author Wenbronk * @Date morning 9:21:59*/@Aspect//Define a slice@Configuration Public classLogaspect {Private StaticFinal Logger Logger = Loggerfactory.getlogger (logaspect.class);//private static final SimpleDateFormat DataFormat = new SimpleDateFormat ("Yyyy-mm-dd ' T ' HH:mm:ss.        SSS "); //Defining tangency Pointcut@Pointcut ("Execution (* com.iwhere.scrapy.controller.*controller.* (..))")     Public voidExcudeservice () {} @Around ("Excudeservice ()")     PublicObject doaround (Proceedingjoinpoint pjp) throws Throwable {Long startTime=System.currenttimemillis (); Requestattributes RA=requestcontextholder.getrequestattributes (); Servletrequestattributes SRA=(servletrequestattributes) RA; HttpServletRequest Request=sra.getrequest (); String URL=Request.getrequesturl (). toString (); String Method=Request.getmethod (); String URI=Request.getrequesturi (); String queryString=request.getquerystring (); Logger.info ("request Start, url: {}, method: {}, Uri: {}, params: {}", url, method, Uri, queryString); //the value of result is the return value of the intercepted methodObject result =pjp.proceed (); Logger.info ("end of request, URL: {}, Response: {}, Time: {}s", URL, json.tojsonstring (Result), (System.currenttimemillis ()-startTime)/ +); returnresult; }    }

You will then need to include a global exception-handling framework:

Http://www.cnblogs.com/wenbronk/p/6850785.html

Specific effects await further testing

SPRINGBOOT-23-ASPECTJ log records and threadlocal memory leaks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.