logging-log4j2 icon indicating copy to clipboard operation
logging-log4j2 copied to clipboard

(doc) Clarify the usage of parameterized logging in `Log4j 2 API` page

Open ppkarwasz opened this issue 1 year ago • 5 comments

The Log4j 2 API documentation page could be improved to state that:

  • parameterized logging and string concatenation should not be mixed, e.g.:
    // This is discouraged, but fine:
    logger.info("Hello " + name + "!");
    // This is recommended:
    logger.info("My name is {}.", myName);
    // Mixing the two approaches: a recipe for pattern specifier injection:
    // E.g. if name contains '{}'.
    logger.info("Hello " + name + "! My name is {}.", myName);
    
  • we could replace the usage of LogManager.getFormatterLogger(Class) with LogManager.getLogger(Class, MessageFormatter), which is more generic.

ppkarwasz avatar Oct 30 '23 10:10 ppkarwasz

@jvz, I assigned this to you since it is related to #2100.

ppkarwasz avatar Dec 15 '23 22:12 ppkarwasz

Not only @jvz but also general documentation - assigned myself too

grobmeier avatar Dec 15 '23 22:12 grobmeier

// Mixing the two approaches: a recipe for pattern specifier injection:
// E.g. if name contains '{}'.
logger.info("Hello " + name + "! My name is {}.", myName);

It would be good to expand on this a bit more, perhaps something like:

Mixing the two approaches can lead to undesired results. For example, let's say that we prompt the user for their name, and they tell us their name is {}. If our log statement looks like the following:

logger.info("Hello " + name + "! My name is {}.", myName);

That results in a log message of "Hello myName! My name is {}".

An MCVE would probably be appropriate here to show the (likely unintended) behavior.

rm5248 avatar Dec 15 '23 22:12 rm5248

* parameterized logging and string concatenation should **not** be mixed, e.g.:
  // This is discouraged, but fine:
  logger.info("Hello " + name + "!");
  // This is recommended:
  logger.info("My name is {}.", myName);
[...]

If this refers to void info(String message, Object p0), then the JavaDoc is misleading. In fact, if message is actually a message template, then the JavaDoc for lots of methods really needs to be fixed.

Chealer avatar Apr 27 '24 02:04 Chealer

That's more of a problem if you mix parameterized logging and concatenated strings. If there are no parameters given, then no parameterized placeholders will be replaced.

jvz avatar May 01 '24 17:05 jvz

Fixed by several changes implemented for #2535.

vy avatar May 24 '24 12:05 vy

As far as I can see this fully persists, but I assume @vy meant that a fix is underway in the staging area. The new Don’t use string concatenation section does improve, but is far from being as clear as @ppkarwasz's suggestion. Note that "using message parameters" is called interpolation: https://en.wikipedia.org/wiki/String_interpolation

Chealer avatar May 25 '24 02:05 Chealer