AOP and filter interception request Print Log Practical example

Source: Internet
Author: User
Tags aop throwable tojson

I am sure you will write some log printing when you write the code, because it is crucial for future operations.

So when we request a restfull interface, what information should be logged?

Here is a basic simple example, here is just an example to illustrate the basic general implementation of the record information, according to the actual situation of the project to choose:

1. HTTP request blocker (filter): Get basic request information from HttpServletRequest

ImportName.ealen.util.HttpUtil;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;ImportOrg.springframework.beans.factory.annotation.Qualifier;ImportOrg.springframework.boot.web.servlet.FilterRegistrationBean;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;ImportOrg.springframework.core.annotation.Order;Importjavax.servlet.*;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjava.io.IOException;/*** Created by Ealenxie on 2018/9/7 15:56. * http request blocker, log print request basic related information*/@Configuration Public classfilterconfiguration {Private Static FinalLogger log = Loggerfactory.getlogger (filterconfig.class); @Bean @Order (Integer.min_value) @Qualifier ("Filterregistration")     PublicFilterregistrationbean filterregistration () {Filterregistrationbean<Filter> registration =NewFilterregistrationbean<>();        Registration.setfilter (Controllerfilter ()); Registration.addurlpatterns ("/*"); returnregistration; }    PrivateFilter Controllerfilter () {return NewFilter () {@Override Public voidInit (filterconfig filterconfig) {log.info ("Controllerfilter init Success"); } @Override Public voidDoFilter (ServletRequest servletrequest, Servletresponse servletresponse, Filterchain chain)throwsIOException, servletexception {httpservletrequest request=(httpservletrequest) ServletRequest; HttpServletResponse Response=(HttpServletResponse) servletresponse; String RequestID= Request.getheader ("Request-id"); if(RequestID = =NULL) RequestID =Request.getrequestedsessionid ();                System.out.println (); Log.info ("Http Request Request-id:" +RequestID); Log.info ("Http Request information: {\" uri\ ": \" "+ request.getrequesturl () +" \ ", \" requestmethod\ ": \" "+ Re                        Quest.getmethod () + "\", \ "clientip\": \ "" + httputil.getipaddress (Request) + "\", \ "content-type\": \ "" + request.getcontenttype () + "\"} ");            Chain.dofilter (request, response); } @Override Public voiddestroy () {Log.info ("Controllerfilter Destroy");    }        }; }}

2. The controller's interception AOP: Gets the requested object, requests the parameters, returns the data, requests the return status, and the internal method takes time.

ImportCom.alibaba.fastjson.JSON;ImportOrg.aspectj.lang.ProceedingJoinPoint;ImportOrg.aspectj.lang.annotation.Around;ImportOrg.aspectj.lang.annotation.Aspect;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.core.env.Environment;ImportOrg.springframework.http.HttpStatus;Importorg.springframework.http.ResponseEntity;Importorg.springframework.stereotype.Component;ImportJavax.annotation.Resource;/*** Created by Ealenxie on 2018/9/7 14:19. * AOP Print log: Requested object, request parameter, return data, request status, internal method time consuming*/@Aspect @component Public classControllerinterceptor {Private Static FinalLogger log = Loggerfactory.getlogger (controllerinterceptor.class); @ResourcePrivateenvironment environment; @Around (Value= "Execution (* name.ealen.web.*.* (..))")     PublicObject Processapifacade (proceedingjoinpoint pjp) {String appName; Try{appName= Environment.getproperty ("Spring.application.name"). toUpperCase (); } Catch(Exception e) {appName= "UNNAMED"; }        LongStartTime =System.currenttimemillis (); String name=pjp.gettarget (). GetClass (). Getsimplename (); String Method=pjp.getsignature (). GetName (); Object result=NULL; Httpstatus Status=NULL; Try{result=pjp.proceed (); Log.info ("Requesttarget:" + AppName + "." + name + "." +method); Log.info ("Requestparam:" +Json.tojson (Pjp.getargs ())); if(Resultinstanceofresponseentity) {Status=((responseentity) result). Getstatuscode (); } Else{Status=Httpstatus.ok; }        } Catch(Throwable throwable) {status=Httpstatus.internal_server_error; Result=NewResponseentity<> ("{\" Internal Server error\ ": \" "+ throwable.getmessage () +" \ "}", status);        Throwable.printstacktrace (); } finally{log.info ("Responseentity: {" + "\" httpstatus\ ": \" "+ status.tostring () +" \ "" + ", \" responsebody\ ":" + json.tojson (Result) + "}"); Log.info ("Internal Method Cost time: {}ms", System.currenttimemillis ()-startTime); }        returnresult; }}

3. Provides a simple Restfull interface:

 PackageName.ealen.web;ImportOrg.springframework.http.HttpStatus;Importorg.springframework.http.ResponseEntity;ImportOrg.springframework.web.bind.annotation.RequestBody;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;/*** Created by Ealenxie on 2018/9/7 14:24.*/@RestController Public classSayhellocontroller {@RequestMapping ("/sayhello")     PublicString SayHello () {return"Hello World"; } @RequestMapping ("/say")     PublicResponseentity<?>Say (@RequestBody Object o) {return NewResponseentity<>(o, Httpstatus.ok); }}

4. Use Postman for basic testing:

5. The console can see the basic effects:

The above is just a simple example of how a controller should log, complete code visible Github.com/ealenxie/springboot-controller-logger

Thank you for your comments and support.

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.