2014-11-02 87 views
1

我正在使用Spring AOP來減少我現有應用程序的調試日誌。基於運行時條件啓用Aspect代理,Spring AOP?

我試圖做的是記錄基於日誌級別的每個方法調用。

我知道春天會,如果我用下面的方面,將會引入一些開銷,如果它不是在調試級別構建一個代理,每類礦井:

package com.basepackage.aop; 

import.... 

@Aspect 
@Component 
public class LogAspect { 

    private Logger logger=Logger.getLogger(LogAspect.class.getName()); 

    @Pointcut("execution(* com.basepackage..*.*(..))")//all the method in my app 
    private void debug_log(){}; 

    @Around("debug_log()")//here, I hope I can introduce something like && logger.isDebugeEnable() 
    public Object aroundLog(ProceedingJoinPoint joinPoint) throws Throwable{ 
     String signature=joinPoint.getSignature().toString(); 
     String paramList = null; 
     Object[] args=joinPoint.getArgs(); 
     for (int i = 0; i < args.length; i++) { 
      paramList+=args[i]+" "; 
     } 

     String debugMsg="----------enter "+signature; 
     if(paramList!=null){ 
      debugMsg+="\nparam: "+paramList; 
     } 

     LogUtil.debug(debugMsg);//will delegate to log4j 
     try{ 
      Object returnObject= joinPoint.proceed(); 
      LogUtil.debug("--------return form"+signature);//will delegate to log4j 
      return returnObject; 
     } 
     catch(Throwable t){ 
      LogUtil.error("--------error from "+signature, t);//will delegate to log4j 
      throw t; 
     } 
    } 
} 

我希望的是,只有當log4j的級別< =調試級別將Spring AOP構造每個類的代理。

或者有關如何使日誌清潔的任何更多的建議將不勝感激。

謝謝!

回答

0

您可以通過添加if()的激活條件,以你的切入點,看到 AspectJ documentation。切入點然後返回boolean代替void,並含有人體動態評估條件並返回結果:

@Pointcut("execution(* com.basepackage..*.*(..)) && if()") 
public boolean debug_log() { 
    return logger.isdebugEnabled(); 
}; 

因爲它是動態的,我想仍然被創建的代理,但諮詢機構將不會執行。爲了擺脫代理,從Spring AOP切換到不使用代理的AspectJ並且更高效。 AspectJ可以通過LTW(加載時織入)輕鬆集成到Apring應用程序中。

更新:

Spring AOP是隻是一個基於代理的「精簡版AOP」的方法攔截,而不是像AspectJ的一個完整的框架方法。因此,它不支持if()切入點基元,請參閱here。話雖如此,我建議你切換到完整的AspectJ。如here所述,它可以通過LTW(加載時編織)輕鬆應用於Spring應用程序。

+0

謝謝!我會嘗試 !但我還有一件事要問,「記錄器」有什麼需要注意的?例如:是否必須是非靜態的,或者必須從哪裏創建(注入,構造函數或其他)? – Jaskey 2014-11-04 04:59:33

+0

我在tomcat中運行應用程序時遇到了一些錯誤,嵌套異常是org.aspectj.weaver.tools.UnsupportedPointcutPrimitiveException:切入點表達式的執行(* wodinow.weixin.jaskey .. *。*(..))&& if ()'包含不受支持的切入點基元'if' – Jaskey 2014-11-04 05:58:58

+0

如果您願意,記錄器可以是靜態的。這個問題與AOP問題無關。 – kriegaex 2014-11-04 12:00:25