How to make Jersey to use SLF4J instead of JUL?

yegor256 picture yegor256 · Nov 8, 2010 · Viewed 13.5k times · Source

I've found a useful article that explains how to make Jersey to use SLF4J instead of JUL. Now my unit test looks like (and it works perfectly):

public class FooTest extends JerseyTest {
  @BeforeClass
  public static void initLogger() {
    java.util.logging.Logger rootLogger =
      java.util.logging.LogManager.getLogManager().getLogger("");
    java.util.logging.Handler[] handlers = rootLogger.getHandlers();
    for (int i = 0; i < handlers.length; i++) {
      rootLogger.removeHandler(handlers[i]);
    }
    org.slf4j.bridge.SLF4JBridgeHandler.install();
  }
  public FooTest() {
    super("com.XXX");
  }
  @Test
  public void testSomething() throws Exception {
    // ...
  }
}

My pom.xml includes these dependencies:

<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>1.6.1</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
  <version>1.6.1</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>jul-to-slf4j</artifactId>
  <version>1.6.1</version>
</dependency>
<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.16</version>
</dependency>

It works perfectly, but I don't want to make the same configuration in every unit test. It's an obvious code duplication, which I would like to avoid. How can I do this more effectively?

ps. Maybe it's not possible to optimize the code above and I'm doing the best I can?

Answer

assylias picture assylias · Sep 29, 2014

If you are using the client API you can manually redirect the logs to slf4j (note that it may break in future versions although it seems unlikely):

Logger LOG = LoggerFactory.getLogger(MyClass.class); //slf4j logger

WebTarget ws = ClientBuilder.newClient(config)
                  .register(new LoggingFilter(new JulFacade(), true));

private static class JulFacade extends java.util.logging.Logger {
  JulFacade() { super("Jersey", null); }
  @Override public void info(String msg) { LOG.info(msg); }
}