Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4j Implicit String Formatting

I am using log4j v1.2.14 for logging in my project and I am also using Java 7 String.format() to put variables in my output. Currently I am writing

LOGGER.info(String.format("Your var is [%s] and you are [%s]", myVar, myVar1));

Is this really the best way to output strings? I feel that log4j should have this implemented implicitly as below:

LOGGER.info("Your var is [%s] and you are [%s]", myVar, myVar1);

Have I missed something? Further, are there any Java logging frameworks that support this?

like image 886
Rossiar Avatar asked Jun 22 '15 08:06

Rossiar


People also ask

How do I format log4j?

Apache log4j provides various Layout objects, each of which can format logging data according to various layouts. It is also possible to create a Layout object that formats logging data in an application-specific way. All Layout objects receive a LoggingEvent object from the Appender objects.


2 Answers

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.

like image 89
Yosef Weiner Avatar answered Oct 24 '22 11:10

Yosef Weiner


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 allocate on the heap 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.

like image 13
Mathieu Avatar answered Oct 24 '22 09:10

Mathieu