Comment #1 on issue 269 by mohammad.nabil.h: Move Logger binding out to
LoggerModule, so users can bind their own Loggers
http://code.google.com/p/google-guice/issues/detail?id=269
A quick hack that works till that fix is released, that won't just give you
context
information about the injectee, but also any additional information (like
the logging
channel).
Using method injection and a simple interceptor ;)
V=========== Sample Usage ================V
private Logger logger;
@Inject
@LogFactory
@LogChannel("Module1LoggingChannel")
@SuppressWarnings("unused")
private void setLogger(Provider<LoggerFactory> loggerFactory, Logger logger)
{
this.logger = logger;
}
private void someMethod()
{
logger.info("i've been called, and the logger have been injected
correctly !");
}
^======== END Sample Usage ==============^
V=========== LoggingModule ===============V
public class LoggerModule extends AbstractModule {
@Override
protected void configure() {
bind(Logger.class).toInstance(
new LoggerFactory().getExceptionThrowingLogger()); // so that if
injection
isn't performed, this logger will produce an exception
bindInterceptor(Matchers.any(), Matchers
.annotatedWith(LogFactory.class), new MethodInterceptor() {
@SuppressWarnings("unchecked")
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Provider<LoggerFactory> provider = (Provider<LoggerFactory>)
invocation
.getArguments()[0]; // injected by guice
String channel = null;
LogChannel lc = invocation.getMethod().getAnnotation(
LogChannel.class);
if (lc != null)
channel = lc.value();
Class clazz = invocation.getMethod().getDeclaringClass();
Logger logger = provider.get().getLogger(clazz, channel);
invocation.getArguments()[1] = logger; // override the
exception-throwing
logger injected by guice !
return invocation.proceed();
}
});
}
}
^=========== END LoggingModule ===========^
It works and everything but adds the burden of adding that dummy method to
every
class you want to log from.
--
You received this message because you are listed in the owner
or CC fields of this issue, or because you starred this issue.
You may adjust your issue notification preferences at:
http://code.google.com/hosting/settings
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"google-guice-dev" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/google-guice-dev?hl=en
-~----------~----~----~----~------~----~------~--~---