Java 8 easy logging
How java 8 lambda lazy evaluation helps in clean logging
code.
The tradition way of logging was to check for a specific level of Log Level and then perform some activity
if(log.isDebugEnabled()){
log.debug("log debug is ", () -> getMessage());
}
Apache logger 2.4 and above supports Lambda expression which can benefit from the lazy evaluation, hence making the if() check unnecessary.
- If the loglevel is not debug then getMessage() function will not be called as lambda functions are evaluated lazy
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.1</version>
</dependency>
</dependencies>
[addToAppearHere]
import org.apache.logging.log4j.LogManager;
import java.util.UUID;
public class Logger {
public static String getMessage() {
return UUID.randomUUID().toString();
}
public static final org.apache.logging.log4j.Logger log = LogManager.getLogger(Logger.class);
public static void main(String[] args) {
log.debug("log debug is ", () -> getMessage());
}
}