Log4j Implicit String Formatting
Using String.format
, +
, or a string formatter other than the one provided by your logging system (log4j
for example) is considered as a bad practice. Usually, in the code there are lots of low level logs (debug, info) you don't want to see in production. If you use for example String.format
to format the string to log, then you will generate and format a new string which can be very long and consume resources, even if at the end nothing will be logged (for example if the log4j
min level is set to warning or error).
By using the logger formatter system (like the one from log4j
), you allow your logger to avoid the generation of the formatted string if it doesn't need to be logged.
This may make a great difference in some cases.
slf4j's api provides "parameterized logging", which allows you to do exactly that, although with a slightly different syntax. The example there is:
logger.debug("Value {} was inserted between {} and {}.", newVal, below, above);
For an implementation, you can use Logback which implements slf4j natively, or the slf4j bindings to connect with log4j or other loggers. The User Manual explains that, along with a short example.
Log4j supports internal formatting. I haven't found it documented anywhere, but I saw an example of it here:
https://logging.apache.org/log4j/2.x/manual/markers.html
I tried it out and it works! I'm on log4j 2.11.2.
int i = 42;
String str1 = "the answer";
String str2 = "life, the universe, and everything";
console.info("{} is {} to {}", i, str1, str2);
Looking at the javadoc for Logger, I'd say it was introduced in Lo4j 2, and supports up to 10 parameters.
https://logging.apache.org/log4j/2.x/log4j-api/apidocs/org/apache/logging/log4j/Logger.html