It is impossible to understand why to use parameterized registration

I read with parameterized logging in Java, they say that it uses parameterized logging instead of concatenation, since it performs a lazy evaluation.

So instead

logger.debug("My text is" + x);

use:

logger.debug("My text is {}", x);

If the trace level is set only for informational logs, why does concatenation occur in the first scenario?

Also, if I have a time function in the log, they say that it uses:

logger.debug("My text is {}", () -> compute());

instead

logger.debug("My text is {}", compute());

In this case, why the lambda method is considered the best approach. Not to calculate can also be called lazy, as in the case of string concatenation?

+4
source share
3 answers

logger.debug(), .

String String ( ). , x .

compute(). , lambda, compute() , compute().

- ( a Supplier, ) , .

+9

. , , , - . :

logger.debug("My text is " + x);

, INFO . , debug, . debug , , INFO. , , , , , . , , ,

if (logger.isDebugEnabled()) {
    logger.debug("My text is " + x)
}

, , , logger.isDebugEnabled() . , logger.debug(). , . , . , , !

+5

, Optional.orElse() vs Optional.orElseGet(), - .

, - :

if(logLevel.isDebug()){

       Value v = supplier.get(); 
       // log v
}

, (, DB call), , , , , .

+1

Source: https://habr.com/ru/post/1685647/


All Articles