Home  >  Q&A  >  body text

java - 为什么Log记录日志要先做一个判断

为什么Log记录日志要先做一个判断了?如下。

   if (logger.isErrorEnabled()){
        logger.error(msg,e);
    }
    
 还有就是logger.isDebugEnabled和logger.isInfoEnable 等等?   
巴扎黑巴扎黑2742 days ago465

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-18 10:57:29

    You can understand it by changing to the following example.

    if (log.isDebugEnabled()) {
        log.debug("log " + param1 + " ...");
    }

    In many cases, some parameter information will be recorded when recording logs. When running online using jcl做为日志接口时难免少不了要拼接字符串,但是日志有不同的级别(level), the normal situation is that all log levels will not be recorded.

    The reasons why you need to add judgment when using jcl时如果不增加日志级别判断。直接这样使用log.debug("log " + param1 + " ...");会产生很多不需要的String对象,这些String实际没有产生作用,浪费了执行时间,同时gc也需要大量回收这种垃圾对象,这也就是在使用jcl.


    Of course we can use it directly nowslf4j利用占位符来减少这种if判断。如log.debug("log {} ...", param1)
    slf4j

    reply
    0
  • Cancelreply