我需要在項目中的某些包中記錄很多類,我無法更改其源代碼。 所以我需要一個解決方案,我可以指定包名稱,並與春天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. 擊日誌記錄,包括行號
- 4. slf4j日誌記錄到特定的包
- 5. log4net - 按用戶日誌記錄
- 6. 日誌記錄當前函數名稱
- 7. ZF2日誌記錄:將自定義信息添加到日誌記錄輸出
- 8. NHibernate:日誌記錄
- 9. WebService日誌記錄
- 10. MongoDB日誌記錄
- 11. Sugarcrm日誌記錄
- 12. SynchronizationLockException +日誌記錄
- 13. Couchdb日誌記錄
- 14. 日誌記錄web.ctx
- 15. 日誌記錄iisreset
- 16. Eazfuscator.NET日誌記錄?
- 17. BlackBerry日誌記錄
- 18. 日誌記錄剛剛出現異常
- 19. 在Perl中輸出日誌記錄
- 20. 去日誌記錄到多個輸出
- 21. 退出appender的日誌記錄
- 22. IntelliJ 14.1 xml日誌記錄輸出
- 23. 在Java中輸出日誌記錄
- 24. JavaScript日誌記錄庫(日誌級別)
- 25. django日誌記錄:未創建日誌
- 26. 沒有日誌庫的日誌記錄
- 27. 使用Python日誌記錄管理日誌記錄器
- 28. 數據庫日誌記錄在日誌記錄過程
- 29. Python日誌記錄不工作 - 日誌記錄對象和sys.modules.pop()
- 30. 調整apache公共日誌記錄的日誌記錄級別?