我需要在项目中的某些包中记录很多类,我无法更改其源代码。 所以我需要一个解决方案,我可以指定包名称,并与春天aop添加日志记录到该包的类没有改变他们,但我不知道我该怎么做。 我该怎么做?按包名弹出日志记录
1
A
回答
1
使用Spring AOP时,如果它们被用作Spring Beans,那么只能记录这些类,即使这样您也只能记录公共方法执行。
这里是@AspectJ通知(这是与“真正的AspectJ”和Spring AOP兼容的样式,阅读有关区别in the spring reference)的一个方面,您可以在Spring AOP和AspectJ字节码编织中使用它:
@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,你得到的方面可视化和测试好的工具。即使您只想使用Spring AOP,也应该阅读AspectJ book。这是一本很棒的书。
顺便说一句:你显然想使用一个真正的记录器,而不是system.out。您可以为每个方面定义一个方面,或者(仅限于真实的aspectj),您可以将其作为目标类中的静态成员引入,以获取每个类的日志记录。在我看来,AspectJ是一个杀手级的特性。
相关问题
- 1. 弹性故障日志记录
- 2. 在gcloud中将日志记录更改为弹性分段日志记录
- 3. Java日志记录:它是日志还是日志记录器?
- 4. SSIS包脚本日志记录
- 5. slf4j日志记录到特定的包
- 6. 击日志记录,包括行号
- 7. 禁用特定包的日志记录
- 8. 拆分包和类日志记录
- 9. NUnit - 如何包含日志记录
- 10. log4net - 按用户日志记录
- 11. 日志记录当前函数名称
- 12. Couchdb日志记录
- 13. SynchronizationLockException +日志记录
- 14. NHibernate:日志记录
- 15. MongoDB日志记录
- 16. Sugarcrm日志记录
- 17. Eazfuscator.NET日志记录?
- 18. WebService日志记录
- 19. Javascript日志记录
- 20. opennms日志记录
- 21. 无记录日志
- 22. Solr日志记录
- 23. 日志记录iisreset
- 24. 日志记录web.ctx
- 25. BlackBerry日志记录
- 26. ZF2日志记录:将自定义信息添加到日志记录输出
- 27. 使用库(名称空间包)进行Python日志记录
- 28. Windsor日志记录工具:控制日志名称
- 29. Apache日志记录日
- 30. 去日志记录到多个输出