Java: Is it possible to automatically add log stat

2019-06-21 20:57发布

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 ?

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.

标签: java logging aop
9条回答
三岁会撩人
2楼-- · 2019-06-21 21:48

As has been suggested to you, AOP fits well to serve this requirement. Not sure what you meant by "having to describe all methods". From what I know there are ways to use wildcards to specify methods to which aspects apply, which could ease your work of "describing"..this is true at least in the case of Spring AOP..not sure about others.

And yes, CGLIB suggested by Maurice is another good candidate for your consideration. Never used it though.

查看更多
该账号已被封号
3楼-- · 2019-06-21 21:50

Try @Loggable annotation from jcabi-aspects (powered by AspectJ):

@Loggable(Loggable.DEBUG)
public String load(URL url) {
  return url.openConnection().getContent();
}

It logs through SLF4J, which you can redirect to your own logging facility like, say, log4j.

查看更多
欢心
4楼-- · 2019-06-21 21:59

Perf4j supports getting timing information for methods using annotations. See here in their developer guide.

查看更多
登录 后发表回答