SLF4J-Log4J did not seem to disable logging

It seems that although the log level was set to INFO, SLF4J still evaluates the expression.

package com.ab.test.slf4j; import org.apache.log4j.PropertyConfigurator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SimpleTest { static final Logger logger = LoggerFactory.getLogger(SimpleTest.class); public static void main(String[] args) { PropertyConfigurator.configure("log4j.properties"); logger.debug("Test " + testEnter()); logger.debug("Test {}", testEnter()); } public static String testEnter() { System.out .println("If you see this it means your expression is evaluated :("); return "test"; } } 

Log4J Property:

 log4j.rootLogger=INFO, CA log4j.appender.CA=org.apache.log4j.ConsoleAppender log4j.appender.CA.layout=org.apache.log4j.PatternLayout log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n 

Run the output:

 If you see this it means your expression is evaluated :( If you see this it means your expression is evaluated :( 

EDIT: the execution output is changed, as you can see, the expression is evaluated, but there is no log message. The expression should not be evaluated as SLF4J Performance Logging

+4
source share
1 answer

This is not slf4j, but the JVM needs to compute each parameter passed before calling the function.

Read this link more carefully. slf4j only skips the toString () call for the object parameters of the skipped log statements. It does not work to miss function calls.

But for this you can create a custom functor object:

  logger.debug(new Object() { @Override public String toString() { return "some expensive test data"; } }); 

The toString () method is called only if debug is not skipped.

+6
source

All Articles