Mikhail Kopylov
Mikhail Kopylov

Reputation: 2058

Logging with aspects

Have a RESTful web-serice with Facade layer, Service layer and Dao layer. Trying to journalize all invokes of all methods of classes, marked with annotation @Log

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
}

Here's the aspect code:

public class LoggingAspect {
  @Around("@target(Log)")
  public Object log(ProceedingJoinPoint pjp) throws Throwable {
    log.debug("Start " + pjp.getSignature().getName());
    Object result = pjp.proceed();
    log.debug("End " + pjp.getSignature().getName());
    return result;
  }
}

Facade, Service and Dao are marked with @Log. Some example:

public Obj Facade.createObj(String name){ //1
  return service.createObj(name);
}

public Obj Service.createObj(String name){ //2
  return dao.createObj(name);
}

public Obj Dao.createObj(String name){ //3
  Long idOfCreatedObj = /*code that creates an object and returns it's ID*/;
  return loadObjById(idOfCreatedObj); /* load the created object by id */
}

public Obj Dao.loadObjById(Long id){ //4
  return /* code that loads the object by it's id */;
}

In this example methods 1, 2, 3 are logged successfully. But the nested dao method (loadObjById) is not logged.

WHY?

P.S. In spring-config.xml there's <aop:aspectj-autoproxy proxy-target-class="true"/>

Upvotes: 0

Views: 2286

Answers (1)

Biju Kunjummen
Biju Kunjummen

Reputation: 49915

The issue is self calls (this.methodcall()) bypass the dynamic/cglib proxy that is created by Spring to handle the cross cutting concern.

The fix is either to use full Aspectj (compile time or load time weaving) or make the call by getting hold of the proxy (instead of alling this.methodCall(), use proxy.methodCall()

You can get hold of the proxy this way:

<aop:aspectj-autoproxy expose-proxy="true"/>

And in your code: AopContext.currentProxy() will give you a reference to the proxy. Here is one blog article on this if you are interested - http://www.java-allandsundry.com/2012/07/reference-to-dynamic-proxy-in-proxied.html

Upvotes: 2

Related Questions