I am starting with java and I try 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 yellow bulb and say: Inefficient use of string concatenation in logger
So I click on "Convert string concatenation to a message template" and it change code to:
_logger.log(Level.INFO, "[{0}] v{1} enabled", new Object[]{car, dog});
That cause problem. Because in log I see: [{0}] v{1} enabled
How to fix it?
All methods on Logger are multi-thread safe.
getLogger(java. lang. String): This method is used to find or create a logger with the name passed as parameter. It will create a new logger if logger does not exist with the passed name.
The info() method of a Logger class is used to Log an INFO message. This method is used to forward logs to all the registered output Handler objects. INFO message: Info is for the use of administrators or advanced users.
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.
It's just helping advice from Netbeans, actually code
_logger.info(car + " text " + dog); // on this line Netbeans
_logger.log(Level.INFO, "{0} text {1}", new Object[]{car, dog});
produce the same output. The first variant more coder friendly less time for typing debug messages, the second awesome.
Any approach that generates the de-parameterized string before determining whether the message should be written is inefficient.
You probably have a poorly written java.util.logging.Formatter
. By that, I mean a formatter that simply output's LogRecord.getMessage()
instead of incorporating LogRecord.getParameters()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With