I am starting with Java and I'm trying to log 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 show me a yellow bulb and say:
Inefficient use of string concatenation in logger
So I clicked on "Convert string concatenation to a message template"
, and it changed code to:
_logger.log(Level.INFO, "[{0}] v{1} enabled", new Object[]{car, dog});
That cause a problem. Because in the logs I see: [{0}] v{1} enabled
.
How to fix it?
You have a few options
1) Use String.format() _logger.log(Level.INFO, String.format("[%s] %s enabled", car, dog))
.
2) Use StringBuilder.append()
or String.concat()`.
Ex: _logger.log(Level.INFO, new StrinBuilder(car).append(" text ").append(dog));
This is essentially what javac does in optimization.
3) Ignore the warning because efficiency is irrelevant for this. If you really cared about speed, you wouldn't be logging things. Logging takes a long time, and the difference between String formatting and String appending is very small relative to the time spent writing the log.