gpt4 book ai didi

java - 如何分解 Java 8 和 SLF4J 中的条件日志检查?

转载 作者:行者123 更新时间:2023-11-29 08:35:02 25 4
gpt4 key购买 nike

我正在尝试分解 if (log.isInfoEnabled())if (log.isWarnEnabled()) 语句,所以我想在中创建一个接口(interface)Java 8 如下所示,但我不确定我是否会遇到任何问题?

public interface Logging {

Logger log_ = LoggerFactory.getLogger(Thread.currentThread().getContextClassLoader().getClass());

default void logInfo(String... messages) {
if (log_.isInfoEnabled()) {
String meg = String.join("log message: ", messages)
log_.info(msg);
}
}
}


public class Hello implements Logging {

//Imagine this function is called lot of times like imagine
// an infinite loop calling this function
public void doSomething(String name) {
if (name.equals("hello")) {
logInfo("What class name does the log print here ? ")
}
}

//Imagine this function is called lot of times like imagine
// an infinite loop calling this function
public void doSomething2(String name) {
if (name.equals("hello2")) {
logInfo("What class name does the log print here ? ")
}
}

//Imagine this function is called lot of times like imagine
// an infinite loop calling this function
public void doSomething3(String name) {
if (name.equals("hello3")) {
logInfo("What class name does the log print here ? ")
}
}
}

对比

public class Hello {

Logger log_ = LoggerFactory.getLogger(Hello.class);

public void doSomething(String name) {
if (name.equals("hello")) {
if (log_.isInfoEnabled()) { // Don't want to have this code everywhere
logInfo("What class name does the log print here ? ")
}
}
}
}

这两个是等价的吗?使用上面的 Logging 接口(interface)有什么问题吗?

最佳答案

守卫(应该)主要用于在不需要时防止代价高昂的操作 - 仅用于调试。

所以下面是正确的模式:

    if (log_.isInfoEnabled()) {
String meg = String.join("log message: ", f(), g(), h);
log_.info(msg);
}

default void logInfo(Supplier<String> messageSupplier) {
if (log_.isInfoEnabled()) {
log_.info(messageSupplier.get());
}
}

logInfo(() -> String.join("log message: ", f(), g(), h));

但是,您冒着将此方法用于简单日志记录情况的风险,将其转换为代价高昂的额外函数调用 logInfo 和 lambda。

关于java - 如何分解 Java 8 和 SLF4J 中的条件日志检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44742944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com