2

I want to make my logging more efficient by using lazy logging in Log4J2.

This means I'm using lambdas, which are only executed when the log level is correct/fulfilled.

Example:

List<Integer> someList = Arrays.asList(1,2,3);
log.info("Size of list is {}.", () -> someList.size());

My IDE tells me, that I can replace this notation with the method reference like so:

log.info("Size of list is {}.", someList::size);

My question is now: Does this approach (method reference) still have the benefit of lazy logging, i.e. that an expensive computational task is only executed in the logging, when the log level is fulfilled or do I lose the whole benefit, when I'm not using lambdas explicitly?

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
Thomas
  • 88
  • 2
  • 11
  • 2
    Short answer: yes. Both the lambda and the corresponding method reference suggested by the IDE end up as an object of the interface type taken by `info()` – ernest_k Jul 09 '19 at 14:03

1 Answers1

1

Take a look at Log4j2 source code, you will find that the Logger class is defining Supplier<?> to make it lazy e.g. in one of the AbstractLogger.logIfEnabled() method you can find:

@Override
public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message,
            final Supplier<?>... paramSuppliers) {
        if (isEnabled(level, marker, message)) {
            logMessage(fqcn, level, marker, message, paramSuppliers);
        }
}

The Supplier<?> will only be invoked if the level is enabled, making it lazy.

It makes no difference if you provide the Supplier using lambda, method reference or by writing new Supplier() { } anonymous class. You can take a look at Do lambda expressions have any use other than saving lines of code? question to understand the subtle differences between these approaches, but the bottom line is that they will be lazy.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • Aren't you actually creating an Array of suppliers here. You are also creating the supplier. So two objects are passed even of the logging level is not enabled? – Kango_V Feb 01 '21 at 14:06