Pau*_* T. 21 java methods logging java.util.logging
现在我java.util.logging用来记录我的Java项目中每个方法的入口和出口点.这在调试时非常有用.
我在每个方法的开头都有这段代码,最后是类似的代码:
if (logger.isLoggable(Level.FINER)) {
logger.entering(this.getClass().getName(), "methodName");
}
Run Code Online (Sandbox Code Playgroud)
其中"methodName"是方法的名称(硬编码).
所以我想知道是否有办法自动执行此操作,而无需在每个方法中包含此代码.
Sal*_*les 13
我建议使用面向方面编程.
例如,使用AspectJ编译器(可以集成到Eclipse,Emacs和其他IDE),您可以创建一段代码,如下所示:
aspect AspectExample {
before() : execution(* Point.*(..))
{
logger.entering(thisJoinPointStaticPart.getSignature().getName(), thisJoinPointStaticPart.getSignature().getDeclaringType() );
}
after() : execution(* Point.*(..))
{
logger.exiting(thisJoinPointStaticPart.getSignature().getName() , thisJoinPointStaticPart.getSignature().getDeclaringType() );
}
}
Run Code Online (Sandbox Code Playgroud)
此方面在"Point"类中执行所有方法之前和之后添加日志记录代码.
正如已经建议的那样,使用带有jcabi-aspects@Loggable注释的AOP (我是开发人员):
@Loggable(Loggable.DEBUG)
public String load(URL url) {
return url.openConnection().getContent();
}
Run Code Online (Sandbox Code Playgroud)
该库还包含一个AOP方面,它可以理解这些注释并通过SLF4J自动记录方法调用,它们的参数和执行时间.
另外,请查看解释详细信息的博文:http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html