Mybaits 基礎組件---日誌分析第三章

LogFactory 日誌工廠

日誌組件: 主要使用的工廠設計模式、適配器設計模式

包目錄
日誌組件
mybaits爲了兼容其他第三方組件,自己定義一個針對於mybaits的通用接口

public interface Log {

  boolean isDebugEnabled();

  boolean isTraceEnabled();

  void error(String s, Throwable e);

  void error(String s);

  void debug(String s);

  void trace(String s);

  void warn(String s);

}

順序加載

 static {
// 第一步: 加載slf4f
    tryImplementation(LogFactory::useSlf4jLogging);
    // 第二步: commonLogging
    tryImplementation(LogFactory::useCommonsLogging);
    // 第三步 log4f2
    tryImplementation(LogFactory::useLog4J2Logging);
    tryImplementation(LogFactory::useLog4JLogging);
    tryImplementation(LogFactory::useJdkLogging);
    tryImplementation(LogFactory::useNoLogging);
  }

如果當前類下有就加載。

myabtis 如果當前類下面無法找到該組件應該怎麼辦

 tryImplementation(LogFactory::useSlf4jLogging);

看一個簡單源碼日誌分析

 public static synchronized void useSlf4jLogging() {
    setImplementation(org.apache.ibatis.logging.slf4j.Slf4jImpl.class);
  }

  private static void setImplementation(Class<? extends Log> implClass) {
    try {
      Constructor<? extends Log> candidate = implClass.getConstructor(String.class);
      Log log = candidate.newInstance(LogFactory.class.getName());
      if (log.isDebugEnabled()) {
        log.debug("Logging initialized using '" + implClass + "' adapter.");
      }
      logConstructor = candidate;
    } catch (Throwable t) {
      throw new LogException("Error setting Log implementation.  Cause: " + t, t);
    }
  }
 private static void tryImplementation(Runnable runnable) {
 // 判斷是否爲null 如果爲null 加載類 如果不爲null 就不加載。
    if (logConstructor == null) {
      try {
      //然後運行該對象
        runnable.run();
      } catch (Throwable t) {
        // ignore
      }
    }
  }

這樣做的目前就是在當前類下面如果沒有找到繼續加載下一個 ( ignore)了異常。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章