SpringAOP實現自動生成日誌

         項目中總要發佈一下服務供系統內外調用,爲了方便排查錯誤,入參出參都要以日誌的形式記錄下來。 
傳統作法:缺點一目瞭然,參數少的時候只能說還好,參數一多,煩不勝煩,浪費時間。
 
Java代碼 
  1. private static final Logger logger = Logger.getLogger(HelloServiceImpl.class);  
  2. public String sayHello(String name,String words) {  
  3.       logger.info("remote input:name="+name+",words="+words);  
  4.       //業務邏輯  
  5.       String result = "Hello"+name+","+words);  
  6.       logger.info("remote output:result="+result);  
  7.       return result;  
  8. }  
         因而基於java.lang.annotation,借鑑AOP的思想,將日誌功能作成一個切面,橫向切入到業務邏輯先後(方法開始前和結束後)。 
        因爲java的反射是不能獲取方法的參數名的,網上有一個第三方工具包JAVAssist提供了現成的方法,但筆者以爲挺麻煩的,決定使用約定優於配置的方式來獲取方法的參數名。你們大概猜到是什麼了吧?對!就是建一個自定義註解。
 
Java代碼 
  1. @Target (ElementType.METHOD)    
  2. @Retention(RetentionPolicy.RUNTIME)    
  3. @Documented    
  4. public @interface  AOPLog4jAnnotation {  
  5.     String paramCollection();  
  6. }  

在須要日誌切面的地方(方法)加上這個註解。  
Java代碼 
  1. public class HelloServiceImpl implements HelloService{  
  2.     @Override  
  3.     @AOPLog4jAnnotation(paramCollection="name,words")  
  4.     public String sayHello(String name,String words) {  
  5.         String text = "Hello "+name+"!"+words+".";  
  6.         return text;  
  7.     }  
  8. }  

         你們也看到了,筆者的這種方式的明顯的缺點:須要按必定規則(把參數按順序填進去,並用英文逗號隔開)把方法參數名配置在註解中。  
Java代碼 
  1. @AOPLog4jAnnotation(paramCollection="name,words")  

惟一的好處是...只須要複製上面這行,而後遵循規則填寫參數名。 
惟二的好處是...日誌格式統一。 
完了,傷心了,感受實用性不強,哎。  
算了,把代碼都貼上吧,留着之後改進。 
Spring配置:
 
Java代碼 
  1. <bean id="helloService" class="com.aop.log4j.service.impl.HelloServiceImpl" />  
  2. <bean id="aspect" class="com.aop.log4j.aspect.HelloAspect"/>  
  3. <aop:config>  
  4.     <aop:pointcut id="pointcut" expression="execution(* com.aop.log4j.service.HelloService.*(..)))" />  
  5.     <aop:aspect ref="aspect">  
  6.         <aop:around pointcut-ref="pointcut" method="arround"/>  
  7.     </aop:aspect>  
  8. </aop:config>  
切面代碼:  
Java代碼 
  1. public class HelloAspect {  
  2.     private static final Logger logger = Logger.getLogger(HelloAspect.class);  
  3.     private static final String DOT = ".";//點號  
  4.     private static final String COMMA = ",";//逗號  
  5.       
  6.     public Object arround(ProceedingJoinPoint joinPoint) throws Throwable {  
  7.         StringBuilder sb = new StringBuilder();  
  8.         Object[] paramValues = joinPoint.getArgs();//獲取參數值  
  9.         String[] paramNames = new String[paramValues.length];  
  10.         Class<? extends Object> invokeClass = joinPoint.getTarget().getClass();  
  11.         String signatureName = joinPoint.getSignature().getName();  
  12.         Method methods[] = invokeClass.getMethods();  
  13.         for (Method method : methods) {  
  14.         if(method.getName().equals(signatureName)) {  
  15.                 String paramCollection = method.getAnnotation  
  16.                       (AOPLog4jAnnotation.class).paramCollection();//獲取註解值  
  17.                 String[] names = paramCollection.split(COMMA);  
  18.                 System.arraycopy(names, 0, paramNames, 0, names.length);  
  19.             }  
  20.         }  
  21.         for (int i = 0; i < paramValues.length; i++) {  
  22.             sb.append(paramNames[i] + "=" + paramValues[i] + COMMA);  
  23.         }  
  24.         //入參日誌  
  25.         logger.info(invokeClass  + DOT + signatureName + ",remote input:"   
  26.                         + sb.toString().substring(0, sb.length() - 1));  
  27.         try {  
  28.            Object result = joinPoint.proceed();  
  29.            //出參日誌  
  30.            logger.info(invokeClass  + DOT + signatureName   
  31.                    + ",remote output:" + result);  
  32.            return result;  
  33.         } catch (Exception e) {  
  34.            logger.error(invokeClass  + DOT + signatureName  
  35.                    + " invoke error");  
  36.         }  
  37.         return null;  
  38.     }  
  39. }  
調用HelloService服務,輸出:  

Java代碼 
  1. [INFO] 2012-10-03 11:54:29,807 [com.aop.log4j.aspect.HelloAspect.arround] - class com.aop.log4j.service.impl.HelloServiceImpl.sayHello,remote input:name=Java,words=I love you.  
  2. [INFO] 2012-10-03 11:54:29,808 [com.aop.log4j.aspect.HelloAspect.arround] - class com.aop.log4j.service.impl.HelloServiceImpl.sayHello,remote output:Hello Java!I love you.  

oschina好像不能插入附件,請移步去個人iteye博客下載吧,謝謝。 java

http://dl.iteye.com/topics/download/0e1af44b-81d0-351c-badb-5e758093767b express

相關文章
相關標籤/搜索