如何将AOP与AspectJ一起使用进行日志记录?

我想将“跟踪”消息添加到我的所有公共方法中,如下所示:


public void foo(s:String,n:int){//日志是log4j记录器或任何其他库

  log.trace(String.format(“使用s输入foo:%s,n:%d”,s,n))

  ...

  log.trace(“退出foo”) 

}

现在,我想log.trace使用AOP(和字节码检测)将所有这些自动添加到我的方法中。我在想AspectJ。是否有意义?您知道开源吗?


MM们
浏览 509回答 3
3回答

心有法竹

我创建了一个简单的方面来捕获公共方法的执行。该AspectJ代码的核心是切入点定义:pointcut publicMethodExecuted(): execution(public * *(..));在这里,我们将捕获具有任何返回类型,任何包和任何类,具有任意数量的参数的所有公共方法。建议的执行情况可以在下面的代码段中看到:after(): publicMethodExecuted() {&nbsp; &nbsp; System.out.printf("Enters on method: %s. \n", thisJoinPoint.getSignature());&nbsp; &nbsp; Object[] arguments = thisJoinPoint.getArgs();&nbsp; &nbsp; for (int i =0; i < arguments.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; Object argument = arguments[i];&nbsp; &nbsp; &nbsp; &nbsp; if (argument != null){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("With argument of type %s and value %s. \n", argument.getClass().toString(), argument);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.printf("Exits method: %s. \n", thisJoinPoint.getSignature());}该建议使用thisJoinPoint获取方法签名和参数。就是这样。这是方面代码:public aspect LogAspect {pointcut publicMethodExecuted(): execution(public * *(..));after(): publicMethodExecuted() {&nbsp; &nbsp; System.out.printf("Enters on method: %s. \n", thisJoinPoint.getSignature());&nbsp; &nbsp; Object[] arguments = thisJoinPoint.getArgs();&nbsp; &nbsp; for (int i =0; i < arguments.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; Object argument = arguments[i];&nbsp; &nbsp; &nbsp; &nbsp; if (argument != null){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("With argument of type %s and value %s. \n", argument.getClass().toString(), argument);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.printf("Exits method: %s. \n", thisJoinPoint.getSignature());}对于更复杂的示例,我会推荐《AspectJ:在行动》一书。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java