Spring AOP configuration slices, log system exceptions to log logs

Source: Internet
Author: User
Tags getmessage log log

1.spring.xml (the main configuration here is the Operation after-throwingafter throwing the exception)

The place to note is highlighted in yellow, mainly several pointcut bean configurations

 <!--Activate automatic proxy function--<aop:aspectj-autoproxy proxy-target-class  = " True "/> <!--slice bean for system service components--<bean id=" aspectservice  " Span style= "COLOR: #0000ff" >class  = " Com.test.http.utils.AspectService  ></bean> <!--AOP configuration--<aop:config> <!--sound A slice, and inject a slice bean, equivalent to @aspect--and <aop:aspect id= "Simpleaspect" ref= "as Pectservice  > <!--Configure a pointcut equivalent to @pointcut---<aop:pointcut expression= execution  (* com.test.http.ser). *(..))" Id= "Simplepointcut"/> <aop:after-throwing  pointcut-ref= "Si Mplepointcut "method=" Afterthrow "throwing=" ex "/> </aop:aspect> </aop:config> 

2.aspectservice.java (This class is a concrete implementation class for facets)

 Packagecom.test.http.utils;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;Importjavax.servlet.http.HttpServletRequest;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;ImportOrg.aspectj.lang.JoinPoint;ImportOrg.springframework.web.context.request.RequestContextHolder;Importorg.springframework.web.context.request.ServletRequestAttributes; Public classAspectservice {Private Final StaticLog log = Logfactory.getlog (aspectservice.class); //Configuring a notification after throwing an exception, using a Pointcut registered on method aspect ()     Public voidAfterthrow (Joinpoint joinpoint, Exception ex) {System.out.println ("Into the tangent afterthrowing method ..."); //judging the log output level        if(log.isinfoenabled ()) {Log.info ("Afterthrow" + joinpoint + "\ T" +ex.getmessage ()); }        //Detailed error InformationString errormsg = ""; Stacktraceelement[] Trace=Ex.getstacktrace ();  for(stacktraceelement s:trace) {errormsg+ = "\tat" + S + "\ r \ n"; } System.out.println ("Specific exception information:" +errormsg); System.out.println ("Afterthrow Exception Method name" + Joinpoint + "\ T" +ex.getmessage ()); System.out.println ("Go to the cutting afterthrowing method end!!!" "); //Write Exception LogWritelog (ERRORMSG,JOINPOINT,EX); }            /**     *      * @paramdetailerrmsg Detailed error information *@paramMethod Name * @Description: Log Exception *@author: Ma * @createTime: 2016-10-14*/     Public voidwritelog (String detailerrmsg,joinpoint joinpoint,exception ex) {HttpServletRequest request=((servletrequestattributes) Requestcontextholder.         Getrequestattributes ()). Getrequest (); //gets the requested URLStringBuffer Requesturl =Request.getrequesturl (); //Get parameter informationString queryString =request.getquerystring (); //encapsulates the full request URL with parameters        if(QueryString! =NULL) {requesturl. Append ("?"). Append (queryString); } String CLA=joinpoint.gettarget (). GetClass (). GetName ();//ActionString method=joinpoint.getsignature (). GetName ();//Method        Try{SimpleDateFormat SDF=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); //Create output Exception Log logFile File =NewFile ("d:/test/" +system.currenttimemillis () +method+ ". Log"); //if file doesnt exists, then create it            if(!file.exists ())            {File.createnewfile (); } FileOutputStream out=NewFileOutputStream (file,false);//true if Append method//Log Specific ParametersStringBuffer sb=NewStringBuffer (); Sb.append ("-----------" +sdf.format (NewDate ()) + "------------\ r \ n"); Sb.append ("Remote request url[" +requesturl+ "]\r\n"); Sb.append ("Interface method: [" +cla+ "." +method+ "]\r\n"); Sb.append ("Verbose error message:" +ex+ "\ r \ n"); Sb.append (detailerrmsg+ "\ r \ n"); Out.write (Sb.tostring (). GetBytes ("Utf-8"));//Note that you need to convert the corresponding character setOut.close (); System.out.println ("Done"); }Catch(IOException e) {e.printstacktrace (); }                    }}

3. Create a test class

 Public void TestMethod (HttpServletRequest request) {      System.out.println ("entry Method");       // System.out.println (Request.getparameter ("username"));      int i = 9/0;}

4. Post-operation log log condition

-----------2016-10-19 14:09:48------------Remote Request Url[http://localhost:8080/httpser/api/testaspect.action?p=111&s=222]specific method: [Com.xx.ad.http.ser.MovCallBackSer.testMethod] Detailed error message: java.lang.ArithmeticException:/by Zero at Com.xx.ad.http.ser.MovCallBackSer.testMethod (Movcallbackser.java:171) at com.xx.ad.http.ser.movcallbackser$ $FastClassBySpringCGLIB $$9be1671c.invoke (<generated>) at Org.springframework.cglib.proxy.MethodProxy.invoke (Methodproxy.java:204) at Org.springframework.aop.framework.cglibaopproxy$cglibmethodinvocation.invokejoinpoint ( Cglibaopproxy.java:717) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (Reflectivemethodinvocation.java: 157) at Org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke (Aspectjafterthrowingadvice.java:58) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (Reflectivemethodinvocation.java: 179) at Org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke (Exposeinvocationinterceptor.java :92) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (Reflectivemethodinvocation.java: 179) at Org.springframework.aop.framework.cglibaopproxy$dynamicadvisedinterceptor.intercept (CglibAopProxy.java: 35V) at com.xx.ad.http.ser.movcallbackser$ $EnhancerBySpringCGLIB $ $b 6f0914c.testmethod (<generated>) at Com.xx.ad.http.controller.ControllerMovCallBack.testAspect (Controllermovcallback.java:71) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke (Nativemethodaccessorimpl.java:57) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Delegatingmethodaccessorimpl.java:43) at Java.lang.reflect.Method.invoke (Method.java:30S) at Org.springframework.web.method.support.InvocableHandlerMethod.doInvoke (Invocablehandlermethod.java: 221) at Org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest ( Invocablehandlermethod.java:137) at Org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle ( Servletinvocablehandlermethod.java:110) at Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod ( Requestmappinghandleradapter.java:776) at Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal ( Requestmappinghandleradapter.java:705) at Org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle ( Abstracthandlermethodadapter.java:85) at Org.springframework.web.servlet.DispatcherServlet.doDispatch (Dispatcherservlet.java:959) at Org.springframework.web.servlet.DispatcherServlet.doService (Dispatcherservlet.java:893) at Org.springframework.web.servlet.FrameworkServlet.processRequest (Frameworkservlet.java:966) at Org.springframework.web.servlet.FrameworkServlet.doGet (Frameworkservlet.java:857) at Javax.servlet.http.HttpServlet.service (Httpservlet.java:620) at Org.springframework.web.servlet.FrameworkServlet.service (Frameworkservlet.java:842) at Javax.servlet.http.HttpServlet.service (Httpservlet.java:727) at Org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (Applicationfilterchain.java:60V) at Org.apache.catalina.core.ApplicationFilterChain.doFilter (Applicationfilterchain.java:208) at Org.apache.tomcat.websocket.server.WsFilter.doFilter (Wsfilter.java:52) at Org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (Applicationfilterchain.java:241) at Org.apache.catalina.core.ApplicationFilterChain.doFilter (Applicationfilterchain.java:208) at Org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal (Characterencodingfilter.java: 85) at Org.springframework.web.filter.OncePerRequestFilter.doFilter (Onceperrequestfilter.java:107) at Org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (Applicationfilterchain.java:241) at Org.apache.catalina.core.ApplicationFilterChain.doFilter (Applicationfilterchain.java:208) at Org.apache.logging.log4j.web.Log4jServletFilter.doFilter (Log4jservletfilter.java:71) at Org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (Applicationfilterchain.java:241) at Org.apache.catalina.core.ApplicationFilterChain.doFilter (Applicationfilterchain.java:208) at Org.apache.catalina.core.StandardWrapperValve.invoke (Standardwrappervalve.java:220) at Org.apache.catalina.core.StandardContextValve.invoke (Standardcontextvalve.java:122) at Org.apache.catalina.authenticator.AuthenticatorBase.invoke (Authenticatorbase.java:40R) at Org.apache.catalina.core.StandardHostValve.invoke (Standardhostvalve.java:170) at Org.apache.catalina.valves.ErrorReportValve.invoke (Errorreportvalve.java:103) at Org.apache.catalina.valves.AccessLogValve.invoke (Accesslogvalve.java:950) at Org.apache.catalina.core.StandardEngineValve.invoke (Standardenginevalve.java:116) at Org.apache.catalina.connector.CoyoteAdapter.service (Coyoteadapter.java:421) at Org.apache.coyote.http11.AbstractHttp11Processor.process (Abstracthttp11processor.java:1070) at Org.apache.coyote.abstractprotocol$abstractconnectionhandler.process (Abstractprotocol.java:611) at Org.apache.tomcat.util.net.aprendpoint$socketprocessor.dorun (Aprendpoint.java:2466) at Org.apache.tomcat.util.net.aprendpoint$socketprocessor.run (Aprendpoint.java:2455) at Java.util.concurrent.ThreadPoolExecutor.runWorker (Threadpoolexecutor.java:1145) at Java.util.concurrent.threadpoolexecutor$worker.run (Threadpoolexecutor.java:615) at Org.apache.tomcat.util.threads.taskthread$wrappingrunnable.run (Taskthread.java:61) at Java.lang.Thread.run (Thread.java:724)

Other facets are equally configurable

Spring AOP configuration slices, log system exceptions to log logs

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.