AOP base logging in Guice

731 views
Skip to first unread message

Ankur Mahajan

unread,
Jul 25, 2016, 7:10:14 AM7/25/16
to google-guice
I am trying to implement AOP based logging in Google - Guice. I have used "MethodInterceptor" for this but it doesn't work. I have used same in Spring by defining point-cuts. Everything is working fine there.

Spring Code for AOP based logging -

@Aspect
public class LoggingAspect {

 
private static Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

   
@Around("requiredLog()")
   
public Object bentoBoxAround(ProceedingJoinPoint proceedingJoinPoint) {

     
Object returnValue = null;
     
try {

          logger
.info("Entered into the method -> " + proceedingJoinPoint.getSignature().toShortString()
                 
+ " and input arguments are -> " + Arrays.asList(proceedingJoinPoint.getArgs()));
          returnValue
= proceedingJoinPoint.proceed();
          logger
.info("Method Execution over !! " + proceedingJoinPoint.getSignature().toShortString());
     
} catch (Throwable e) {
          logger
.error("Method has an exception " + e.getMessage());
     
}
     
return returnValue;
   
}

   
@Pointcut("within(org.cal.bento..*)")
   
public void allRequiredPakageLog() {
   
}

 
}


From above code we can log all the class and method executions inside the "org.cal.bento.*" package.

Guice code for AOP based logging -

public class GuiceLoggingInterceptor implements MethodInterceptor {

 
private static Logger logger = LoggerFactory
 
.getLogger(GuiceLoggingInterceptor.class);

 
@Override
 
public Object invoke(MethodInvocation invocation) throws Throwable {
   
Object returnValue = null;
   
try {
        logger
.info("GUICE - Entered into the method -> " + invocation.getMethod().getName()
                   
+ " and input arguments are -> " + Arrays.asList(invocation.getArguments()));
        returnValue
= invocation.proceed();
        logger
.info("Method Execution over !! " + invocation.getMethod().getName());
   
} catch (Throwable e) {
        logger
.error("GUICE - Method has an exception " + e.getMessage());
   
}
   
return returnValue;
 
}
}

Binding Class - 

public class GuiceAopModule extends AbstractModule {

 
@Override
 
protected void configure() {
      bindInterceptor
(Matchers.any(), Matchers.any(), new GuiceLoggingInterceptor());
 
}
}

Can we do similar in Guice for logging (write only one Aspect based class for whole logging system). I don't want to modify every class.
Any help would be highly appreciated.

Olivier Grégoire

unread,
Jul 25, 2016, 7:21:30 AM7/25/16
to google-guice
You should use another class Matcher. Currently you configured your binder to adapt all injected classes, no matter where they're located.

To do what you want, you should change your binding to the following:

    bindInterceptor(Matchers.inSubpackage("org.cal.bento"), Matchers.any(), new GuiceLoggingInterceptor());

--
You received this message because you are subscribed to the Google Groups "google-guice" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-guice...@googlegroups.com.
To post to this group, send email to google...@googlegroups.com.
Visit this group at https://groups.google.com/group/google-guice.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-guice/23ee65b0-983b-47db-81f1-06d9ed618b69%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Message has been deleted

Ankur Mahajan

unread,
Jul 25, 2016, 7:44:00 AM7/25/16
to google-guice
Hi Olivier,

Thanks for the reply, I've tried what you suggested but No LUCK :(
Could you please suggest something else which would work like charm :).

Olivier Grégoire

unread,
Jul 25, 2016, 8:20:17 AM7/25/16
to google-guice
Hello,


Your problem then isn't with Guice but probably with your logger. As proof, here's a working example. Feel free to directly adapt it.

com/example/logged/Echoer.java

package com.example.logged;

public class Echoer {
  public String echo(String s) { return String.format("echo %s", s);  }
}

com/example/notlogged/Printer.java

package com.example.notlogged;

public class Printer {
  public String print(String s) { return String.format("print %s", s); }
}

com/example/Main.java

package com.example;

import com.example.logged.Echoer;
import com.example.notlogged.Printer;
import com.google.inject.*;
import com.google.inject.matcher.Matchers;
import org.aopalliance.intercept.*;
import java.util.Arrays;

public class Main {
  @Inject Echoer echoer;
  @Inject Printer printer;
  public static void main(String[] args) {
    Main app = Guice.createInjector(new AbstractModule() {
      @Override
      protected void configure() {
        bindInterceptor(Matchers.inSubpackage("com.example.logged"), Matchers.any(), new MethodInterceptor() {
          @Override
          public Object invoke(MethodInvocation mi) throws Throwable {
            System.out.printf("Calling method %s with arguments %s%n", mi.getMethod().getName(), Arrays.toString(mi.getArguments()));
            try {
              Object returnValue = mi.proceed();
              System.out.printf("Method %s returned %s%n", mi.getMethod().getName(), returnValue);
              return returnValue;
            } catch (Throwable t) {
              System.out.printf("Method %s threw an exception %s%n", mi.getMethod().getName(), t);
              throw t;
            }
          }
        });
      }
    }).getInstance(Main.class);
    System.out.println(app.echoer.echo("foo"));
    System.out.println(app.printer.print("bar"));
  }
}

The result is :

Calling method echo with arguments [foo]
Method echo returned echo foo
echo foo
print bar

It is expected that this is the correct result, since we only wrap around the package "com.example.logged" which contains the class Echoer, not the class Printer.


--
You received this message because you are subscribed to the Google Groups "google-guice" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-guice...@googlegroups.com.
To post to this group, send email to google...@googlegroups.com.
Visit this group at https://groups.google.com/group/google-guice.

Ankur Mahajan

unread,
Jul 27, 2016, 2:05:46 AM7/27/16
to google-guice
Hi Olivier,

Thanks for replying, I finally figure out this thing. In my case spring is loading all the dependencies of Guice so I made some configuration changes and It start working.
Reply all
Reply to author
Forward
0 new messages