How to check info log level enabled in Java.util.logging
Asked Answered
C

2

5

How to check whether a certain logging level is enabled before actually logging debug statements?

Commodious answered 3/6, 2016 at 10:44 Comment(1)
Hint: it is very safe to assume that "reasonable" functionality already exists for most components that come "built-in" with Java - just because that stuff is in use for years, and has sometimes seen many updates to make it "as perfect as possible". So, yes, asking questions here is nice; but reading javadoc first, trying google second ... is very often more efficient than writing up a SO question first ...Cementum
P
6

Yes it provides -

Logger#isLoggable(Level level)

Check if a message of the given level would actually be logged by this logger. This check is based on the Loggers effective level, which may be inherited from its parent.

documentation

Pavior answered 3/6, 2016 at 10:49 Comment(3)
Yes it is, #6504907Commodious
The only reason that might make sense: performance optimization. If the computation of the string to be logged is expensive, well, then maybe you really want to only spent CPU cycles on that computation ... if the result is really required.Cementum
Even for optimization purposes it is not necessary anymore with Java 8 lambdas. You can simply create your complex String as described in this answer.Gamble
C
1

Using Simple Logging Facade for Java or (SLF4J) - http://www.slf4j.org/faq.html#logging_performance Checking logging level can be completely avoided. In case of parameterized messages

Object entry = new SomeObject();
logger.debug("The entry is {}.", entry);

After evaluating whether to log or not, and only if the decision is affirmative, will the logger implementation format the message and replace the '{}' pair with the string value of entry. In other words, this form does not incur the cost of parameter construction in case the log statement is disabled.

The following two lines will yield the exact same output. However, the second form will outperform the first form by a factor of at least 30, in case of a disabled logging statement.

logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);
Chadchadabe answered 25/6, 2021 at 12:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.