user1768830
user1768830

Reputation:

SLF4J API Loggers: Singletons or Multitons?

When you have SLF4J's API jar (slf4j-api-x.x.x.jar) and a binding on your runtime class path, you can use code like:

Logger logger = LoggerFactory.getLogger(getClass());
logger.debug("Some debug message");

Does SLF4J conveniently cache Logger instances (based on the specied class) for you, or is it just returning a new Logger every time?

For instance, if I have:

Logger logger1 = LoggerFactory.getLogger(Widget.class);
Logger logger2 = LoggerFactory.getLogger(Widget.class);
Logger logger3 = LoggerFactory.getLogger(Widget.class);
logger1.debug("Some debug message");

Are the loggers (logger1, logger2 and logger3) all the same instance/memory reference or are they 3 separate logger instances, all configured to log on behalf of the Widget class?

Upvotes: 0

Views: 1030

Answers (3)

user1768830
user1768830

Reputation:

Yes SLF4J does perform caching on the loggers.

Upvotes: 1

Evgheni Crujcov
Evgheni Crujcov

Reputation: 470

You can easily test that yourself. Just make a check logger1 == logger2 == logger3. If Logger is an instance-controlled class which caches and reuses its instances, the references will point to the same object. If, instead it returns a new logger every time, your check would return false.

Upvotes: 0

Eric Stein
Eric Stein

Reputation: 13672

All three should be references to the same object. Note that this is trivial to test for yourself with logger1 == logger2.

Upvotes: 0

Related Questions