buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

强迫症犯了,忍不住赞一下slf4j包Logger.java的优雅代码

如下是slf4j-api包下的Logger接口类里其中几个方法的声明:

package org.slf4j;

public interface Logger {
    /**
    * Log a message at the INFO level.
    *
    * @param msg the message string to be logged
    */
    public void info(String msg);
    /**
    * Log a message at the INFO level according to the specified format and argument.
    *
    * @param format the format string
    * @param arg    the argument
    */
    public void info(String format, Object arg);
    /**
    * Log a message at the INFO level according to the specified format and arguments.
    *
    * @param format    the format string
    * @param arguments a list of 3 or more arguments
    */
    public void info(String format, Object... arguments);

    
    /**
    * Log a message at the ERROR level.
    *
    * @param msg the message string to be logged
    */
    public void error(String msg);
    public void error(String format, Object arg);
    public void error(String format, Object... arguments);
    
    /**
    * Log an exception (throwable) at the ERROR level with an accompanying message.
    *
    * @param msg the message accompanying the exception
    * @param t   the exception (throwable) to log
    */
    public void error(String msg, Throwable t);
}

 

slf4j(Simple Logging Facade for Java)是Facade模式的典型应用,它定义了一套标准的日志接口,诸如logback、log4j、slf4j-simple等框架都是这个日志接口的具体实现。从这一点来看,slf4j的标准化显得相当重要,当然,从上面这些方法可见,它做到了!

我这里要点赞的也是这几个方法的签名。注意观察比较这几个info/error方法的第一个参数的名字:有的是format,有的是msg。同样是String类型,不同的是根据这两个参数命名,我们可以得知传递什么样的值。msg就是一段文本,而format则可以是一段包含了占位符“{}”的文本。充分展现了代码的整洁之道,由此可以看出来作者是很讲究代码的可读性。

看上面几个方法,

  • 如果记录异常信息,不妨调用error(String msg, Throwable t)方法。这时,第一个参数不是format,是msg。所以下面语句里的“{}”就有画蛇添足之嫌了:
try {
    ......
    }
} catch (IOException e) {
    LOG.error("#PayCenterHttpTransport,http调用出错!异常信息:{}", e);
}
  • 如果要打印更详细的info日志,可以调用logger.info那几个重载方法,支持用format形式。
log.info("融宝请求url:{},请求报文:{}", url, json);
  • logger.error也是支持format的。如下是Logger接口类里这个error重载方法的定义。注意调用方式是 log.error("执行请求{}出现异常,",1,new Exception("test")); 
  /**
   * Log a message at the ERROR level according to the specified format and arguments.
   * <p/>
   * <p>This form avoids superfluous object creation when the logger is disabled for the ERROR level. </p>
   *
   * @param format the format string
   * @param arg1   the first argument
   * @param arg2   the second argument
   */
  public void error(String format, Object arg1, Object arg2);

打印的异常日志是:

14:55:25.997 [main] ERROR ddd - 执行请求1出现异常,
java.lang.Exception: test
	at com.emax.paycenter.common.util.MailUtil.main(MailUtil.java:100) [classes/:na]

 

 

=====EOF=====

posted on 2018-03-08 10:21  buguge  阅读(1790)  评论(0编辑  收藏  举报