Java 8您可以使用lambdas/供应商:

Java 8您可以使用lambdas/供应商:,java,logging,lazy-evaluation,Java,Logging,Lazy Evaluation,logger.log(Level.FINER,()->String.format(“某些操作%s需要%04dms才能完成”,名称,持续时间)) ()->…在这里充当供应商,将被延迟评估。延迟评估的问题正是slf4j的{}语法被引入的原因,在其他方面很好,但我仍然坚持使用log4j。我有一种复杂的日志设置,所以我不能把slf4j放进去。slf4j对log4j有一个绑定。因此,无论您的“复杂日志设置”是什么,SLF4J都能很好地处理它。只有在需要惰性字符串求值时,才能继续直接使用log4j和SLF4

logger.log(Level.FINER,()->String.format(“某些操作%s需要%04dms才能完成”,名称,持续时间))


()->…
在这里充当供应商,将被延迟评估。

延迟评估的问题正是slf4j的{}语法被引入的原因,在其他方面很好,但我仍然坚持使用log4j。我有一种复杂的日志设置,所以我不能把slf4j放进去。slf4j对log4j有一个绑定。因此,无论您的“复杂日志设置”是什么,SLF4J都能很好地处理它。只有在需要惰性字符串求值时,才能继续直接使用log4j和SLF4J。最后一个示例不应该是logger.debug(lazyFormat(“调试消息是%s”,someMessage))@朱哈:是的,你说得对。在我发布答案后,我注意到了一点错误,所以它已经被修复了。更新版本的Log4J允许参数替换请看这是否真的有效——它将格式化字符串,但它是否在做“懒惰”的事情?我做了一个小测试,lazyFormat的args是对打印到System.err的函数的调用,它看起来像对象中的args。。。即使String.format(s,o)不是.OneSolitaryNoob,也要进行求值-它不是在做懒惰的事情。答案提供程序指出,可以通过使用toString()方法中的“isDebugEnabled()”方法来完成。在我的回答中,我提供了一个更通用的延迟日志模式:Scala怎么样?您的示例有点误导,因为您的未格式化示例和格式化示例之间几乎没有区别;i、 e.格式化程序中没有user.getName()或user.getId()操作的实际值,因为它们被立即调用,并且它们的值被传递到logger.debug方法。最初的海报传递了两个对象实例,因为除非需要,否则不会调用这些实例上的toString()方法。我在
logger.debug中发布了一个答案,更准确地捕获了这个“仅在使用数据时才调用数据”state.Log4j 2.4.In
logger.debug(“使用id{}登录用户{}”,user.getName(),user.getId())
get
方法将在运行
logger.debug()
之前立即调用,要完成log4j的惰性模式,您需要:
logger.debug(“使用id{}登录用户{},()->user.getName(),()->user.getId())
if(logger.isDebugEnabled() ) {
   logger.debug(String.format("some texts %s with patterns %s", object1, object2));
}
logger.debug(lazyFormat("some texts %s with patterns %s", object1, object2));
LOGGER.debug("this is my long string {}", fatObject);
 public class LazyFormat {

    public static void main(String[] args) {
        Object o = lazyFormat("some texts %s with patterns %s", "looong string", "another loooong string");
        System.out.println(o);
    }

    private static Object lazyFormat(final String s, final Object... o) {
        return new Object() {
            @Override
            public String toString() {
                return String.format(s,o);
            }
        };
    }
}
System.out.println(lazyFormat(true, "Hello, %s.", "Bob"));
System.out.println(lazyFormat(false, "Hello, %s.", "Dave"));
Hello, Bob.
null
private String lazyFormat(boolean format, final String s, final Object... o) {
  if (format) {
    return String.format(s, o);
  }
  else {
    return null;
  }
}
logger.debug(lazyFormat(logger.isDebugEnabled(), "Message: %s", someValue));
private static String lazyFormat(final String s, final Object... o) {
  if (logger.isDebugEnabled()) {
    return String.format(s, o);
  }
  else {
    return null;
  }
}
logger.debug(lazyFormat("Debug message is %s", someMessage));
public class Log4jWrapper {

    private final Logger inner;

    private Log4jWrapper(Class<?> clazz) {
        inner = Logger.getLogger(clazz);
    }

    public static Log4jWrapper getLogger(Class<?> clazz) {
        return new Log4jWrapper(clazz);
    }

    public void trace(String format, Object... args) {
        if(inner.isTraceEnabled()) {
            inner.trace(String.format(format, args));    
        }
    }

    public void debug(String format, Object... args) {
        if(inner.isDebugEnabled()) {
            inner.debug(String.format(format, args));    
        }
    }

    public void warn(String format, Object... args) {
        inner.warn(String.format(format, args));    
    }

    public void error(String format, Object... args) {
        inner.error(String.format(format, args));    
    }

    public void fatal(String format, Object... args) {
        inner.fatal(String.format(format, args));    
    }    
}
private final static Log4jWrapper logger = Log4jWrapper.getLogger(ClassUsingLogging.class);
logger.debug("User {0} is not authorized to access function {1}", user, accessFunction)
debug(logger, "some texts %s with patterns %s", object1, object2);
public static void debug(Logger logger, String format, Object... args) {
    if(logger.isDebugEnabled()) 
       logger.debug(String.format("some texts %s with patterns %s", args));
}
if (logger.isDebugEnabled()) {     
  logger.debug("Logging in user " + user.getName() + " with id " + user.getId()); 
} 
logger.debug("Logging in user {} with id {}", user.getName(), user.getId()); 
LOGGER.debug("some texts {} with patterns {}", object1, object2);
    class SimpleSfl4jLazyStringEvaluation {
      private static final Logger LOGGER = LoggerFactory.getLogger(SimpleSfl4jLazyStringEvaluation.class);

      ...

      public void someCodeSomewhereInTheClass() {
//all the code between here
        LOGGER.debug(
            "{}"
          , new Object() {
              @Override
              public String toString() {
                return "someExpensiveInternalState=" + getSomeExpensiveInternalState();
              }
            }
//and here can be turned into a one liner
        );
      }

      private String getSomeExpensiveInternalState() {
        //do expensive string generation/concatenation here
      }
    }
LOGGER.debug("{}", new Object(){@Override public String toString(){return "someExpensiveInternalState=" + getSomeExpensiveInternalState();}});
LogSF.debug(log, "Processing request {}", req);
 LogMF.debug(logger, "The {0} jumped over the moon {1} times", "cow", 5);