SLF4J-Log4J does not appear to have disabled logging

我是研究僧i 提交于 2020-01-03 13:36:50

问题


It seems that although the log level was set to INFO, SLF4J is still evaluating 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 file:

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 output:

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

EDIT: Amended the run output, as seen, the expression is evaluated, however the log message is not. Expression should not be evaluated as per SLF4J's "Performance Logging"


回答1:


It's not slf4j but JVM need to compute every passed parameter before function call.

Read the given link more carefully. slf4j only skips calling toString() for Object params of skipped log statements. It's not working for skipping function calls.

But you can create custom functor object for this:

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

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



来源:https://stackoverflow.com/questions/8643654/slf4j-log4j-does-not-appear-to-have-disabled-logging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!