2009-03-20

Bridging java.util.logging to SLF4J

This little code snippet will pass everything logged using java.util.logging (JUL) to SLF4J AND remove JUL's default Handler, so to avoid having everything logged twice:

// Jersey uses java.util.logging - bridge to slf4
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();

The reason I'm posting this is that it took me a little longer than expected to write it. I've never really used JUL, but I've recently been working on a small JAX-RS application using the Jersey framework.

Jersey uses JUL as it's logging framework. The rest of the application uses SLF4J and Logback, so I wanted everything logged using JUL redirected to SLF4J. For that purpose the SLF4J project provides jul-to-slf4j.jar and the class SLF4JBridgeHandler as described here.

According to the above mentioned site all that's required is to call SLF4JBridgeHandler.install(), and that also works very well, except it just installs an extra Handler on JUL's root logger - it dosn't remove the handler which is there by default. That also makes sense, but since I've never used JUL it took me a while to figure out how to make it stop logging anything. I've seen a lot of people asking how to "replace" JUL logging with SLF4J, and answers was far fewer, so I thought I'd share my solution.