To pass an argument that will executed in a lazy way the String
computation, you have to pass a Supplier
and not a String
.
The method that you invoke should have this signature :
void debug(Supplier<?> msgSupplier, Throwable t)
You could introduce this utility method in your own utility class.
But you should not need to do that as recent logging frameworks such as Log4j2 provides this feature out of the box.
For example, org.apache.logging.log4j.Logger provides overloaded methods to log that accept a Supplier
.
For example :
void debug(MessageSupplier msgSupplier, Throwable t)
Logs a message (only to be constructed if the logging level is the
DEBUG level) including the stack trace of the Throwable t passed as
parameter. The MessageSupplier may or may not use the MessageFactory
to construct the Message.
Parameters
:
msgSupplier
- A function, which when called, produces the desired log
message.
t
- the exception to log, including its stack trace.
From Log4j2 documentation :
Java 8 lambda support for lazy logging
In release 2.4, the Logger interface added support for lambda
expressions. This allows client code to lazily log messages without
explicitly checking if the requested log level is enabled. For
example, previously you would write:
if (logger.isTraceEnabled()) {
logger.trace("Some long-running operation returned {}", expensiveOperation());
}
With Java 8 you can achieve the same effect with a lambda expression.
You no longer need to explicitly check the log level:
logger.trace("Some long-running operation returned {}",
() -> expensiveOperation());