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.
9 comments:
Thanks very much for posting this!
Thanks. I found this through Ehcache's site, and it's really useful.
While SLF4JBridgeHandler provides a quick fix, if it is installed multiple times, then one is bound to run into trouble. Imagine an application with several web-applications each installing SLF4JBridgeHandler.
On a slightly different register, SLF4JBridgeHandler involves measurable overhead. I would not recommend using it if a large of logging events go through it.
Hey, thanks for posting this. I was wondering why SLF4JBridgeHandler wasn't doing what I expected. The code snippet was very helpful.
Still very helpful two years later, thanks a lot!
Thanks for sharing!
How about
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
Thanks Jens, that is certainly simpler. The removeHandlersForRootLogger method wasn't there when I wrote this blog entry, but now I have updated it.
Thank you, removeHandlersForRootLogger() did the trick for me and removed the annoying console output.
Post a Comment