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

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

问题描述

我想在我的所有公共方法中添加trace消息,如下所示:

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") 
}

现在我想添加所有 log.trace 使用AOP(和字节代码检测)自动使用我的方法。我在考虑 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. \n", 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. \n", argument.getClass().toString(), argument);
        }
    }

    System.out.printf("Exits method: %s. \n", 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. \n", 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. \n", argument.getClass().toString(), argument);
        }
    }
    System.out.printf("Exits method: %s. \n", thisJoinPoint.getSignature());
}

对于更复杂的例子,我建议书 AspectJ:在行动中

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

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

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