Do logger always read debug even if level is set to info and does it have any significant impact?

Logging classes are just normal Java classes.

If you have a method call in your code, it will be called.

However… all logging frameworks’ log methods are designed to return immediately if the relevant level is not enabled, which makes the entire method call have so little cost it’s essentially nothing. For that reason, you almost never should use if (debug) or if (logger.isDebugEnabled()). They aren’t saving any time at all.

However, normal Java methods are still normal Java methods. When you execute this:

LOGGER.debug(model.toString());

Java will first invoke model.toString(), then pass the result of that to the logger. Unlike the logger call, that toString can be expensive, if the toString method does a lot of work and/or is called very frequently. To address this, logging frameworks have parameterized log methods, which will convert arguments to strings only if the relevant level is enabled.

Using java.util.logging.Logger, it looks like this:

logger.log(Level.FINE, "Model={0}", model);     // no toString() call

Using SLF4J or Log4j:

logger.debug("Model={}", model);                 // no toString() call

Tags:

Java

Logging