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屋!