Foreword: Now there is a system, mainly in order to provide data query interface for other systems, this system will not be easily updated on-line, and will not follow the update of the Business system and update (this is also a data query interface system reasons, decoupling). At this point, the system needs to have a certain convenient online error-checking, I think of logging every time the call log, and need to record the error stack, but also by the White list filter to be recorded.
Idea
This logging needs to be logged every time the interface is accessed, and the exception stack information is recorded in each access record when there is an exception. This is because the database information is used, so the spring interceptor is selected.
After the interceptor is relieved, run the business code, if thrown exception (including custom exceptions), should be thrown after the exception, log the error message to the stack, you need to know the interceptor when the database inserted the ID of the record, get this ID can directly update the data, the stack record. This is done by ThreadLocal thread Local variables to record the primary key ID returned after each access to the inserted database.
And each time the exception needs to do a uniform exception handling, in the Unified exception processing here to access the database, log error messages.
The whitelist is filtered to be recorded, and this is best handled by throwing custom business exceptions and then using the uniform exception class.
Realize
The interface call log requires a table to record, and the fields are as follows:
Create TableT_interface_log (ID Number not NULL, Interface_namevarchar2( -), Caller_ipvarchar2( -), Local_ipvarchar2( -), Caller_paramsvarchar2( +), Caller_date date, msgvarchar2(4000), Statusvarchar2(1));--Add comments to the tableComment on TableT_interface_log is 'interface invoke logging table';--Add Comments to the columnsComment on columnt_interface_log.id is 'primary Key ID'; Comment on columnT_interface_log.interface_name is 'Interface Name'; Comment on columnt_interface_log.caller_ip is 'Caller IP'; Comment on columnt_interface_log.local_ip is 'Native IP'; Comment on columnT_interface_log.caller_params is 'Calling Parameters'; Comment on columnt_interface_log.caller_date is 'Call Time'; Comment on columnt_interface_log.msg is 'Information Logging'; Comment on columnT_interface_log.status is 'Status: 0: Failure, 1: Success';
The configuration is as follows:
<BeanID= "Interfaceloginterceptor"class= "Com.yule.common.interceptor.InterfaceLogInterceptor" /> <mvc:interceptors> <Mvc:interceptor> <mvc:mappingPath= "/interface/**"/> <refBean= "Interfaceloginterceptor" /> </Mvc:interceptor> </mvc:interceptors>
The Java code is as follows:
Thread variables
Packagecom.yule.manage.interfacelog.entity;/*** Interface Call log thread variable *@authorYule*/ Public classInterfacelogholder {/*** Local thread variable, used to control the ID returned after each new log*/ Private Static FinalThreadlocal<string> id_string_thread_local =NewThreadlocal<>(); /*** Gets the ID of the local thread variable *@returnID*/ Public StaticString Getidstringthreadlocalvalue () {returnId_string_thread_local.get (); } /*** Set the ID of the local thread variable *@paramValue ID*/ Public Static voidSetidstringthreadlocalvalue (String value) {Id_string_thread_local.set (value); } /*** Remove current local thread variable from current thread*/ Public Static voidremovestringthreadlocal () {id_string_thread_local.remove (); }}
Interception device
PackageCom.yule.common.interceptor;ImportCom.ch.common.util.CommonTool;ImportCom.yule.manage.interfacelog.entity.InterfaceLog;ImportCom.yule.manage.interfacelog.entity.InterfaceLogHolder;ImportCom.yule.manage.interfacelog.service.InterfaceLogService;Importorg.apache.commons.lang3.StringUtils;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.web.servlet.handler.HandlerInterceptorAdapter;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportJava.util.Map;/*** Log blocker: Record Call log *@authorYule*/ Public classInterfaceloginterceptorextendsHandlerinterceptoradapter {@AutowiredPrivateInterfacelogservice Interfacelogservice; Private FinalLogger Logger = Loggerfactory.getlogger (interfaceloginterceptor.class); @Override Public BooleanPrehandle (httpservletrequest request, httpservletresponse response, Object handler)throwsException {Try{interfacelog Interfacelog=NewInterfacelog (); Interfacelog.setstatus (interfacelog.status_success); //method returns the IP address of the client that made the requestInterfacelog.setcallerip (Request.getremoteaddr ()); Interfacelog.setinterfacename (Request.getrequesturi ());//Interfacelog.setlocalip (Request.getlocaladdr ());//method returns the IP address of the Web server. //returns a enumeration object that contains all the parameter names in the request message. By traversing the enumeration object, you can get all the parameter names in the request message. map<string, string[]> paramsmap =Request.getparametermap (); if(Commontool.isnotnullorblock (Paramsmap)) {StringBuilder StringBuilder=NewStringBuilder (); for(Map.entry<string, string[]>Entry:paramsMap.entrySet ()) {Stringbuilder.append (Entry.getkey ()). Append (":"). Append (Stringutils.join (Entry.getvalue ())). Append (";"); } interfacelog.setcallerparams (Stringbuilder.tostring ()); } This. Interfacelogservice.insert (Interfacelog); //thread variable stored valueInterfacelogholder.setidstringthreadlocalvalue (Interfacelog.getid ()); } Catch(Exception e) {logger.error ("Error message logged by interface call, caller IP:" + request.getremotehost () + ", caller IP:" + request.getremoteaddr () + ", Interface name:" +Request.getrequesturi (), E); } return true; }}
Unified exception Handling
Packagecom.yule.common.dealexception;Importcom.yule.common.entity.ResponseBase;ImportCom.yule.manage.interfacelog.entity.InterfaceLog;ImportCom.yule.manage.interfacelog.entity.InterfaceLogHolder;ImportCom.yule.manage.interfacelog.service.InterfaceLogService;ImportCom.yule.interfacepackage.pibdata.web.ctrl.PibDataCtrl;Importorg.apache.commons.lang3.exception.ExceptionUtils;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.web.bind.annotation.ControllerAdvice;ImportOrg.springframework.web.bind.annotation.ExceptionHandler;ImportOrg.springframework.web.bind.annotation.ResponseBody;Importjavax.servlet.http.HttpServletRequest;/*** Interface Unified exception handling, and log error logs *@authorYule*/@ControllerAdvice ("Com.yule.interfacepackage") Public classdealinterfaceexception {@AutowiredPrivateInterfacelogservice Interfacelogservice; PrivateLogger Logger = Loggerfactory.getlogger (dealinterfaceexception.class); @ExceptionHandler @ResponseBody Publicresponsebase dealexception (httpservletrequest request, Exception ex) {//Exception HandlingLogger.error (Ex.getmessage (), ex); Responsebase Responsebase=Newresponsebase (); Responsebase.seterrormsg (Ex.getmessage ()); Responsebase.setsuccess (false); This. Interfacelogservice.update (Exceptionutils.getstacktrace (ex), Interfacelog.status_error, Interfacelogholder.getidstringthreadlocalvalue ()); returnresponsebase; }}
Working experience: The Java system records the call log and logs the error stack