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

2024-01-10

看起来虽然日志级别设置为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 的“性能日志记录” http://www.slf4j.org/faq.html#logging_performance


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

更仔细地阅读给定的链接。 slf4j 仅跳过对跳过的日志语句的对象参数调用 toString() 。它不适用于跳过函数调用。

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

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

仅当不跳过调试时才会调用 toString() 方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SLF4J-Log4J 似乎没有禁用日志记录 的相关文章

随机推荐