Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 965
user1571252 Avatar asked Sep 07 '12 18:09

user1571252


People also ask

Is java logger thread safe?

All methods on Logger are multi-thread safe.

What is logger getLogger in java?

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.

What does logger info do in java?

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.


3 Answers

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.

like image 125
Ryan Amos Avatar answered Oct 17 '22 14:10

Ryan Amos


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.

like image 24
Roman C Avatar answered Oct 17 '22 14:10

Roman C


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()

like image 25
Dilum Ranatunga Avatar answered Oct 17 '22 12:10

Dilum Ranatunga