Currently SLF4JLogger in Log4j 2 will format all messages before it passes
these to SLF4J. I think this does not need to be the case.

SLF4J FAQ <https://www.slf4j.org/faq.html#string_contents> states that:
"Assuming complexObject is an object of certain complexity, for a log
statement of level DEBUG, you can write:

logger.debug("{}", complexObject);

The logging system will invoke complexObject.toString() method only after
it has ascertained that the log statement was enabled. Otherwise, the cost
of complexObject.toString() conversion will be advantageously avoided."

When Log4j 2 wraps the Message, SLF4J can invoke the formatting
conditionally by a call of the overridden toString().

I would like to provide a pull request if this is an acceptable change.
Example sketch:
Slf4jMessageAdapter messageToBeFormatted = new Slf4jMessageAdapter(message);
// ...
logger.debug(slf4jMarker, "{}", messageToBeFormatted, t);

private static class Slf4jMessageAdapter {

  private Message message;

  private Slf4jMessageAdapter(Message message) {
    this.message = message;
  }

  @Override
  public String toString() {
    return message != null ? message.getFormattedMessage() : null;
  }
}

Cheers!

Benjamin

Reply via email to