Search code examples
javaloggingaop

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 ?

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.


Solution

  • 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.