如何使用 AOP 和 AspectJ 进行日志记录? [英] How to use AOP with AspectJ for logging?

查看:31
本文介绍了如何使用 AOP 和 AspectJ 进行日志记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to add "trace" messages to all my public methods as follows:

public void foo(s:String, n:int) { // log is a log4j logger or any other library
  log.trace(String.format("Enter foo with s: %s, n: %d", s, n))
  ...
  log.trace("Exit foo") 
}

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

Now I would like to add all those log.trace to my methods automatically with AOP (and byte code instrumentation). I am thinking about AspectJ. Does it make sense? Do you know any open-source, which does exactly that?

推荐答案

我创建了一个简单的方面来捕获公共方法的执行.这段 AspectJ 代码的核心是切入点定义:

I have created a simple aspect to capture the execution of public methods. The core of this AspectJ code is the pointcut definition:

pointcut publicMethodExecuted(): execution(public * *(..));

在这里,我们捕获具有任何返回类型、任何包和任何类、具有任意数量参数的所有公共方法.

Here we are capturing all public methods with any return type, on any package and any class, with any number of parameters.

建议执行可以在下面的代码片段中可视化:

The advice execution could be visualized on code snippet below:

after(): publicMethodExecuted() {
    System.out.printf("Enters on method: %s. 
", thisJoinPoint.getSignature());

    Object[] arguments = thisJoinPoint.getArgs();
    for (int i =0; i < arguments.length; i++){
        Object argument = arguments[i];
        if (argument != null){
            System.out.printf("With argument of type %s and value %s. 
", argument.getClass().toString(), argument);
        }
    }

    System.out.printf("Exits method: %s. 
", thisJoinPoint.getSignature());
}

此建议使用 thisJoinPoint 来获取方法签名和参数.就是这样.这是方面代码:

This advice use thisJoinPoint to get the method signature and arguments. And that's it. Here is the aspect code:

public aspect LogAspect {

pointcut publicMethodExecuted(): execution(public * *(..));

after(): publicMethodExecuted() {
    System.out.printf("Enters on method: %s. 
", thisJoinPoint.getSignature());

    Object[] arguments = thisJoinPoint.getArgs();
    for (int i =0; i < arguments.length; i++){
        Object argument = arguments[i];
        if (argument != null){
            System.out.printf("With argument of type %s and value %s. 
", argument.getClass().toString(), argument);
        }
    }
    System.out.printf("Exits method: %s. 
", thisJoinPoint.getSignature());
}

对于更复杂的例子,我会推荐这本书 AspectJ: In行动.

For more complex examples I would recommend the book AspectJ: In Action.

这篇关于如何使用 AOP 和 AspectJ 进行日志记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆