CustomInjections for log4j2

I tried to follow the CustomInjections documentation , but updating it for log4j2. I seem to be missing the InjectLogger class.

Any ideas what I missed, or does anyone have a working example I see?

+3


source to share


1 answer


InjectLogger

is a custom annotation type that you define yourself.

Here's a quick example:

Log4j2CustomInjection.java

package test.guice;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.matcher.Matchers;

public class Log4j2CustomInjection {

  public static void main(String[] args) {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(PaymentService.class).asEagerSingleton();
                bindListener(Matchers.any(), new Log4JTypeListener());
              }
            });

    PaymentService ps = injector.getInstance(PaymentService.class);
    ps.logger.info("hello");
  }
}

      

PaymentService.java

package test.guice;

import org.apache.logging.log4j.Logger;

public class PaymentService {
  @InjectLogger Logger logger;
}

      



InjectLogger.java

package test.guice;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface InjectLogger {}

      

Log4JTypeListener.java

package test.guice;

import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;
import java.lang.reflect.Field;
import org.apache.logging.log4j.Logger;

class Log4JTypeListener implements TypeListener {
  public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
    Class<?> clazz = typeLiteral.getRawType();
    while (clazz != null) {
      for (Field field : clazz.getDeclaredFields()) {
        if (field.getType() == Logger.class && field.isAnnotationPresent(InjectLogger.class)) {
          typeEncounter.register(new Log4JMembersInjector<>(field));
        }
      }
      clazz = clazz.getSuperclass();
    }
  }
}

      

Log4JMembersInjector.java

package test.guice;

import com.google.inject.MembersInjector;
import java.lang.reflect.Field;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

class Log4JMembersInjector<T> implements MembersInjector<T> {
  private final Field field;
  private final Logger logger;

  Log4JMembersInjector(Field field) {
    this.field = field;
    this.logger = LogManager.getLogger(field.getDeclaringClass());
    field.setAccessible(true);
  }

  public void injectMembers(T t) {
    try {
      field.set(t, logger);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }
}

      

+2


source







All Articles