SLF4J-Log4J似乎没有禁用日志记录

时间:2011-12-27 10:32:31

标签: java logging log4j slf4j

虽然日志级别设置为INFO,但SLF4J仍在评估表达式。

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属性文件:

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

运行输出:

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

编辑:修改了运行输出,如图所示,计算表达式,但日志消息不是。不应按SLF4J's "Performance Logging"

评估表达式

1 个答案:

答案 0 :(得分:6)

这不是slf4j,但JVM需要在函数调用之前计算每个传递的参数。

仔细阅读给定的链接。 slf4j只跳过调用toString()获取跳过的日志语句的Object参数。它不能用于跳过函数调用。

但您可以为此创建自定义仿函数对象:

    logger.debug(new Object() {
        @Override
        public String toString() {
            return "some expensive test data";
        }
    });
只有在不跳过debug时才会调用

toString()方法。