I set the logger settings to INFO level, and ran the following test:
@Test
void loggerTest() {
System.out.println("START " + LocalDateTime.now());
System.out.println("TRACE: " + LocalDateTime.now());
log.trace("{}", sleepAndReturnString(5000L, "TRACE PRINT"));
System.out.println("DEBUG: " + LocalDateTime.now());
log.debug("{}", sleepAndReturnString(5000L, "DEBUG PRINT"));
System.out.println("INFO: " + LocalDateTime.now());
log.info("{}", sleepAndReturnString(5000L, "INFO PRINT"));
System.out.println("WARN: " + LocalDateTime.now());
log.warn("{}", sleepAndReturnString(5000L, "WARN PRINT"));
System.out.println("ERROR: " + LocalDateTime.now());
log.error("{}", sleepAndReturnString(5000L, "ERROR PRINT"));
System.out.println("END " + LocalDateTime.now());
}
public static String sleepAndReturnString(long millis, String message) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
log.error("", e);
}
return message;
}
logback.xml file:
<configuration>
<property name="MY__PATTERN"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} | %highlight(%-5level) | %message%n%rEx"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<outputPatternAsHeader>true</outputPatternAsHeader>
<pattern>${MY__PATTERN}</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="CONSOLE"/>
</root>
Here is what was printed in the console:
START 2023-01-20T11:17:57.255
TRACE: 2023-01-20T11:17:57.255
DEBUG: 2023-01-20T11:18:02.256
INFO: 2023-01-20T11:18:07.262
2023-01-20 11:18:12.267 | INFO | INFO PRINT
WARN: 2023-01-20T11:18:12.283
2023-01-20 11:18:17.285 | WARN | WARN PRINT
ERROR: 2023-01-20T11:18:17.285
2023-01-20 11:18:22.287 | ERROR | ERROR PRINT
END 2023-01-20T11:18:22.287
As we can see, each time the thread fell asleep for 5 seconds, although the TRACE and DEBUG messages were not printed to the console. This suggests that the use of isLevelEnabled is justified, and increases performance.