Java:是否可以自动向方法添加日志语句? [英] Java: Is it possible to automatically add log statements to methods?
问题描述
我的应用程序中的大多数方法都是这样编写的:
Most of the methods in my application are written like this:
public void m() {
long t1 = System.currentTimeMillis();
log.info("begin - m()");
/* method body */
long t2 = System.currentTimeMillis();
log.info("end - m(), took " + (t2 - t1) + "ms.");
}
我希望我可以简单地注释我的方法并自动生成日志语句:
I wish I could simply annotate my method and have the log statements be automagically generated instead:
@Log("executionTime")
public void m() {
/* method body */
}
关于如何继续使用这种方法的任何想法?有什么已知的解决方案吗?
Any ideas on how to proceed with this approach ? Is there any known solution ?
有人为此建议了 AOP.问题是,使用 AspectJ 或 Spring AOP,我必须描述所有方法,这些方法与方法本身中的日志调用一样多.
Someone suggested AOP for this. The problem is that with AspectJ or Spring AOP I would have to describe all the methods which ammounts to as much code as the log calls in the method itself.
推荐答案
AspectJ 和
execution(* com.company.project..*.*(..))
将覆盖project
的所有子包中的所有方法.所以不需要一一定义所有方法.
which will cover all methods in all sub-packages of project
. So no need to define all methods one by one.
这篇关于Java:是否可以自动向方法添加日志语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!