按包名称进行Spring记录

时间:2010-08-24 08:33:48

标签: java spring logging aop spring-aop

我需要在项目中的某些包中记录许多类,我无法更改其源代码。 所以我需要一个解决方案,我可以指定包名,并使用spring aop添加日志记录到该包的类而不更改它们但我不知道我该怎么做。 我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

使用Spring AOP,只有在将这些类用作Spring Bean时才能记录这些类,即使这样,您也只能记录公共方法执行。

这是@AspectJ通知中的一个方面(这是与“真实的AspectJ”和Spring AOP兼容的样式,读取可以在Spring AOP和AspectJ字节中使用的差异in the spring reference)代码编织:

@Aspect
public class LoggingAspect{

    @Pointcut("execution(* com.mycompany.myproject.*.*(..))")
    public void methodToLog(){
    };

    @Around("methodToLog()")
    public Object logMethod(final ProceedingJoinPoint joinPoint) throws Throwable{
        final StaticPart staticPart = joinPoint.getStaticPart();
        final String sig =
            "" + staticPart.getSignature() + " with args: "
                + Arrays.deepToString(joinPoint.getArgs());
        System.out.println("Entering method " + sig);
        final Object result = joinPoint.proceed();
        System.out.println("Leaving method " + sig);
        return result;
    }

}

这是一个带有一些方法的愚蠢类:

package com.mycompany.myproject;
public class Dummy1{

    public static void main(final String[] args){
        final Dummy1 dummy = new Dummy1();
        dummy.doSomeStuff();
        dummy.doSomeStuffWithSomeArgs("Hello", 123);
    }

    private void doSomeStuff(){}

    public void doSomeStuffWithSomeArgs(final String firstArg,
        final int secondArg){}

}

当您在Eclipse / AJDT中将此类作为Java / AspectJ应用程序启动时,您将获得以下输出:

Entering method void com.mycompany.myproject.Dummy1.main(String[]) with args: [[]]
Entering method void com.mycompany.myproject.Dummy1.doSomeStuff() with args: []
Leaving method void com.mycompany.myproject.Dummy1.doSomeStuff() with args: []
Entering method void com.mycompany.myproject.Dummy1.doSomeStuffWithSomeArgs(String, int) with args: [Hello, 123]
Leaving method void com.mycompany.myproject.Dummy1.doSomeStuffWithSomeArgs(String, int) with args: [Hello, 123]
Leaving method void com.mycompany.myproject.Dummy1.main(String[]) with args: [[]]

要在Spring中测试这个,AOP会涉及更多的工作(主方法方法不起作用,你必须创建一个ApplicationContext并注册一个Dummy1类型的bean,你将在其上调用方法),所以我'将它留给你,但我很确定不会记录私有方法调用。

如果您下载SpringSource Tool Suite,您将获得用于方面可视化和测试的漂亮工具。您还应该阅读AspectJ book,即使您只想使用Spring AOP。这是一本很棒的书。


顺便说一句:你显然想要使用真正的记录器,而不是system.out。您可以为每个方面定义一个,或者(仅使用真实的aspectj)可以将其作为目标类中的静态成员引入以获取每个类的日志记录。在我看来,AspectJ的一个杀手级功能。