Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Is it possible to automatically add log statements to methods?

Tags:

java

logging

aop

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.

like image 611
Leonel Avatar asked Jan 18 '10 13:01

Leonel


2 Answers

AspectJ and Spring AOP support something like:

execution(* com.company.project..*.*(..))

which will cover all methods in all sub-packages of project. So no need to define all methods one by one.

like image 177
Bozho Avatar answered Sep 30 '22 04:09

Bozho


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.

like image 35
Aadith Ramia Avatar answered Sep 30 '22 06:09

Aadith Ramia