Java Logger - Netbeans hint "Inefficient use of string concatenation in the log"

I start with java and I am trying to do something.

private static final Logger _logger = Logger.getLogger("my"); String car = "bmw"; String dog = "dog"; _logger.info(car + " text " + dog); // on this line Netbeans 

.. on this line, Netbeans will show me a yellow lamp and say: Inefficient use of string concatenation in the log

So, I click "Convert string concatenation to message template" and change the code to:

 _logger.log(Level.INFO, "[{0}] v{1} enabled", new Object[]{car, dog}); 

This is causing a problem. Because in the log I see: [{0}] v{1} enabled How can I fix this?

+6
source share
4 answers

You have several options.

1) Use String.format () _logger.log(Level.INFO, String.format("[%s] %s enabled", car, dog)) .

2) Use StringBuilder.append() or String.concat () `.

Example: _logger.log(Level.INFO, new StrinBuilder(car).append(" text ").append(dog));

This is essentially what javac does in optimization.

3) Ignore the warning, because it does not matter the effectiveness. If you really care about speed, you won’t register things. Logging takes a lot of time, and the difference between formatting strings and adding a string is very small relative to the time taken to write the log.

+9
source

It just helps Netbeans tips, actually the code

 _logger.info(car + " text " + dog); // on this line Netbeans _logger.log(Level.INFO, "{0} text {1}", new Object[]{car, dog}); 

give the same result . The first option, which is more convenient for the encoder, has less time for entering debugging messages, the second is amazing.

+1
source

Any approach that generates a deparameterized string before deciding whether a message should be written is inefficient.

Probably your java.util.logging.Formatter is badly written. By this I mean a formatter that simply outputs LogRecord.getMessage() instead of including LogRecord.getParameters()

+1
source

This is the actual formatting of netbeans 7.1.2 do

 public class Vels4j { private static final Logger _logger = Logger.getLogger("my"); String car = "bmw"; String dog = "dog"; Vels4j() { // _logger.info(car + " text " + dog); _logger.log(Level.INFO, "{0} text {1}", new Object[]{car, dog}); } public static void main(String[] args) { Vels4j vels4j = new Vels4j(); } } 

You can turn off the tips if you do not want to. You can also customize the tooltip.

0
source

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


All Articles