log4j 禁止类输出日志,SLF4J-Log4J似乎没有禁用日志记录

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"

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值