60

I am using slf4j for logging in my application. I get the purpose of slf4j. I would like to know how to find out which logging-library slf4j is currently binding to. I have log4j in my referenced libraries. I am assuming that slf4j has bound itself to log4j.

What I would like to know is, is there any way to explicitly confirm this binding?

1
  • 1
    I swear there was a way to turn on slf4j debugging (meta debugging) but I can't remember what it was. None of the answers address that. Commented Jan 15, 2019 at 23:25

5 Answers 5

73

Just do what SLF4J does to discover the binding:

final StaticLoggerBinder binder = StaticLoggerBinder.getSingleton();

Now you can try to find out what is the actual implementation in my case:

System.out.println(binder.getLoggerFactory());
System.out.println(binder.getLoggerFactoryClassStr());

This prints:

ch.qos.logback.classic.LoggerContext[default]
ch.qos.logback.classic.selector.DefaultContextSelector
Sign up to request clarification or add additional context in comments.

4 Comments

How can I find which jar file the logger (logback in the above example) came from?
@Jason how about asking the class loader?
How do I ask the class loader?
StaticLoggerBinder is not part of slf4j-api, so this method does not work.
8

The StaticLoggerBinder's getLoggerFactoryClassStr() method is probably what you're looking for.

Comments

5

Easy. Put a breakpoint on .. say.. LOG.info(...). Once debugger stops there, step into.. and viola.. you will find yourself in the code of the actual logger... say log4j or logback.. whatever.

Serious answer. JVM picks up from classpath in order. Say if it encounters java.util.logging first, it will look for logging.properties configuration file. If all is well, it will use this and look no further. If not, then it will go ahead and say, find log4j.jar. JVM will look for log4j.xml. If all set, no mistakes, then this wil be selected, and so on.
You can also give hints to JVM on which configuration file to use so that the particular logger gets selected, using -D vm args. Each logger has its own.

Comments

4

It's possible to do this using the main slf4j public API (i.e. without the internal StaticLoggerBinder), e.g. to detect if slf4j has bpound to log4j2:

if ("org.apache.logging.slf4j.Log4jLoggerFactory".equals(
    org.slf4j.LoggerFactory.getILoggerFactory().getClass().getName()
) 
{ ... }

Comments

2

Or, avoiding the need to have StaticLoggerBinder (which is not part of slf4j-api):

log.info(log.getClass().getName());

In my case this prints

ch.qos.logback.classic.Logger

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.