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?
What it sounds like is you'd want the JUL/SLF4J configuration handle before JUnit starts testing so it could be covered for all tests? Here's a way you could do that.
Output
Code
This worked for me:
and then having my tests extend
JerseyTestSFL4J
.The best way to do it is through a custom Listener. Being initialized before JSF servlet it should configure jul-to-slf4j bridge in
contextInitialized(ServletContextEvent)
.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):
In my app Jersey logging (with proper
pom.xml
andlogback.xml
) works fine only withFor tests you can make base abstract test with common configuration and extends other JUnit from it:
Slf4jLogger
fromorg.apache.cxf:cxf-core
package is another option. It implementsjava.util.logging.Logger
and delegate cals to slf4J.Jersey server:
Jersey client: