JAVA implementation Common Logging __java

Source: Internet
Author: User

Objective:
Previously wanted to filter the filter layer directly httpserverletrequest request for log processing, but then getwriter () when the report
already been call exception. Checked, only to find the original flow form can only read once. It's like food, it's gone.
So there is no way to log in filter and inteceptor by getting the stream of request.

So it is ready to use the common method: Controller layer AOP to make slice logging. using AOP to record action logs First step: Add AOP

/** * Unified Log Processing Handler * @author mingchenchen * */public class Logaophandler {@Autowired private Auditlogdao a

    Uditlogdao; /** * Controller level record operation log * Note that this is aop:around because of the need to get the parameters before the request and the result of the interface returned after the request * @throws throwable * * * publi C Object Dosavelog (Proceedingjoinpoint joinpoint) throws Throwable {Methodsignature method = (methodsignature) j
        Oinpoint.getsignature ();
        String methodname = Method.getname ();
        Object[] objects = Joinpoint.getargs ();
        String requestbody = null;  if (objects!=null && objects.length>0) {for (object object:objects) {if (object = = null) {requestbody = Null;//post interface parameter is empty such as delete xxx}else if (object instanceof String {requestbody = (String) object;//some interfaces directly convert arguments to objects}else {reques
                Tbody = Jsonobject.tojsonstring (object);

     }
            }
        }   Log Boolean Isneedsavelog = False that only logs the Post method; Getannotationbytype is not a JAVA8 feature here, because annotations can duplicate names, so the array requestmapping annotation = Method.getmethod () is obtained. Getannotatio
        N (requestmapping.class);
                For (Requestmethod RequestMethod:annotation.method ()) {if (requestmethod==requestmethod.post) {
            Isneedsavelog = true;
        } jsonobject Requestbodyjson = null;
        try {Requestbodyjson = Jsonobject.parseobject (requestbody); catch (Exception e) {//do Nothing that post request did not pass body} httpservletrequest request = Requestconte
        Xtutil.getrequestbycurrentcontext ();
        String userName = Requestcontextutil.getusernamebycurrentcontext (); if (Stringutil.isempty (userName)) {try {userName = Dmscache.get (Requestbodyjson.getstring ("U
            Sername ")). GetName (); catch (Exception e) {userName = Requestcontextutil.getasYnuserinfobyautodeploy (). GetName (); }///Get the request's parameter and let the method execute it//note that the around needs to return result otherwise it will not return the value to the requestor Object, result = Joinpoin
        T.proceed (objects);
            try {jsonobject Resultjson = Jsonobject.parseobject (result.tostring ()); if (Isneedsavelog) {//If it is a POST request log logtypeenum Logtypeenum = Logtypeenum.getdesbymethodname (methodname)
                ;
                    if (logtypeenum!= null) {auditlogentity auditlogentity = new auditlogentity ();
                    Auditlogentity.setuuid (Stringutil.createrandomuuid ());
                    Auditlogentity.setoperator (UserName);
                    Auditlogentity.setrequestip (Request.getremoteaddr ());
                    Auditlogentity.setrequesturl (Request.getrequesturi (). Replace ("/cloud-master", ""));
                    Auditlogentity.seteventtype (Logtypeenum.getkey ());
   Auditlogentity.seteventdesc (Logtypeenum.getdescription ());                 Auditlogentity.setrequest (Requestbody); int issuccess = "equals" (Resultjson.getstring ("code"))?
                    1:0;
                    Auditlogentity.setsuccessflag (issuccess);
                    Auditlogentity.setresponse (Result.tostring ());
                    Auditlogentity.setcreatetime (New Date ());
                Auditlogdao.insert (auditlogentity);
        A catch (Exception e) {e.printstacktrace ());
    return result;

 }  
}
Step two: Declare in spring's XML
    <!--record operation log-->
    <bean id= "OPERATIONLOGAOP" class= "
     Com.ming.learn.core.aop.LogAopHandler"/> <aop:config>
       <aop:aspect id= "LOGAOP" ref= "OPERATIONLOGAOP" >
         <aop:pointcut id= "Target" expression= "Execution (* com.ming.learn). *controller.* (..)) " />
         <aop:around method= "Dosavelog" pointcut-ref= "target"/>
       </aop:aspect>
     </AOP: Config>

As a result, the core steps are complete, and the rest is to assemble the things that need to be recorded. Step three: Write Dao, Entity, Mapper

Import Java.util.Date;
Import Javax.persistence.Column;
Import Javax.persistence.Id;

Import javax.persistence.Table; /** * Log Audit * @author Mingchenchen */@Table (name= "Audit_log") public class Auditlogentity {@Id private stri

    ng UUID; @Column (name= "Event_type") private string eventtype;//event type @Column (name= "Event_desc") private string Eventdes c;//Event Chinese Description @Column (name= "operator") private String operator;//operator @Column (name= "request_ip") Private Str
    ing requestip;//client address @Column (name= "Request_url") private String requesturl;//request address @Column (name= "request") private string request;//request body @Column (name= "response") private string response;//request return value @Column (name= "Cr

    Eate_time ") Private Date createtime;
    Public String Getuuid () {return UUID;
    public void Setuuid (String uuid) {this.uuid = UUID;
    Public String Geteventtype () {return eventtype; } public void SEteventtype (String eventtype) {this.eventtype = EventType;
    Public String Geteventdesc () {return eventdesc;
    } public void Seteventdesc (String eventdesc) {this.eventdesc = Eventdesc;
    Public String Getoperator () {return operator;
    } public void Setoperator (String operator) {this.operator = operator;
    Public String Getrequestip () {return requestip;
    } public void Setrequestip (String requestip) {this.requestip = Requestip;
    Public String Getrequesturl () {return requesturl;
    } public void Setrequesturl (String requesturl) {this.requesturl = Requesturl;
    Public String Getrequest () {return request;
    public void Setrequest (String request) {this.request = Request;
    Public String GetResponse () {return response; } public void Setresponse (String response) {This.response =Response
    Public Date Getcreatetime () {return createtime;
    The public void Setcreatetime (Date createtime) {this.createtime = Createtime;
 }
}
Step Fourth: Customize the response's event type according to the Controller method name
Import Java.util.Map;

Import Java.util.concurrent.ConcurrentHashMap;
    /** * Operation Log type * @author mingchenchen * */public enum Logtypeenum {//user Common_login ("login", "login", "login"); Other private string methodname;//method names are saved to the database by the controller consistent private string key;//the event type private string Descrip tion;//the description saved to the database private Logtypeenum (String methodname,string key,string description) {this.methodname = Metho
        Dname;
        This.key = key;
    this.description = description;
    Public String Getmethodname () {return methodname;
    } public void Setmethodname (String methodname) {this.methodname = methodname;
    Public String Getkey () {return key;
    public void Setkey (String key) {this.key = key;
    Public String GetDescription () {return description;
    } public void SetDescription (String description) {this.description = description; }/** * Returns * by method name * @Param methodname * @return * * public static Logtypeenum Getdesbymethodname (String methodname) {retur
    N InnerMap.map.get (methodname); /** * Internal class user saves all enums without passing through enum.values () each traversal * @author Mingchenchen */private static Clas

        s innermap{private static map<string, logtypeenum> Map = new concurrenthashmap<> (128); static{//Initializes the entire enumeration class to the map for (Logtypeenum logTypeEnum:LogTypeEnum.values ()) {map.
            Put (Logtypeenum.getmethodname (), logtypeenum);
 }
        }
    }
}

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.