如何在Java中自动记录方法的进入/退出? [英] How to automatically log the entry/exit of methods in Java?
问题描述
现在我正在使用 java.util.logging
来记录我的Java项目中每个方法的入口和出口点。这在调试时非常有用。
Right now I am using java.util.logging
to log the entry and exit points of each method in my Java project. This is very useful to me when debugging.
我在每个方法的开头都有这段代码,最后有类似的代码:
I have this piece of code at the beginning of each method and a similar one at the end:
if (logger.isLoggable(Level.FINER)) {
logger.entering(this.getClass().getName(), "methodName");
}
其中methodName是方法的名称(硬编码)。
Where "methodName" is the the name of the method (hardcoded).
所以我想知道是否有办法自动执行此操作,而无需在每种方法中都包含此代码。
推荐答案
我建议使用面向方面编程。
I suggest the use of Aspect Oriented Programming.
例如,使用 AspectJ 编译器(可以集成到Eclipse,Emacs和其他IDE),你可以像这样创建一段代码这一个:
For example, using the AspectJ compiler (which can be integrated to Eclipse, Emacs and others IDEs), you can create a piece of code like this one:
aspect AspectExample {
before() : execution(* Point.*(..))
{
logger.entering(thisJoinPointStaticPart.getSignature().getName(), thisJoinPointStaticPart.getSignature().getDeclaringType() );
}
after() : execution(* Point.*(..))
{
logger.exiting(thisJoinPointStaticPart.getSignature().getName() , thisJoinPointStaticPart.getSignature().getDeclaringType() );
}
}
这方面添加了一个日志代码并且在Point类中执行所有方法之前。
This aspect adds a logging code after and before the execution of all methods in the class "Point".
这篇关于如何在Java中自动记录方法的进入/退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!