日志那些事兒——slf4j集成logback/log4j

前言

日志Logger漫談中提到了slf4j僅僅是作為日志門面,給用戶提供統(tǒng)一的API使用,而真正的日志系統(tǒng)的實現(xiàn)是由logback或者log4j這樣的日志系統(tǒng)實現(xiàn),那究竟slf4j是怎樣集成logback或者log4j的呢?

集成logback

前文中提到,如果要使用slf4j+logback,需要引入slf4j-api及l(fā)ogback-classic、logback-core三個jar包。

  • 我們一般這樣使用
Logger logger = LoggerFactory.getLogger("logger1");
logger.info("This is a test msg from: {}", "LNAmp");
  • LoggerFactory.getLogger的源代碼如下:
public static Logger getLogger(String name) {
    ILoggerFactory iLoggerFactory = getILoggerFactory();
    return iLoggerFactory.getLogger(name);
  }

需要注意的是,Logger、LoggerFactory、ILoggerFactory都是slf4j-api.jar中的類或接口。
從源碼看來,獲取Logger有兩個過程,現(xiàn)獲取對應(yīng)的ILoggerFactory,再通過ILoggerFactory獲取Logger

public static ILoggerFactory getILoggerFactory() {
    if (INITIALIZATION_STATE == UNINITIALIZED) {
      INITIALIZATION_STATE = ONGOING_INITIALIZATION;
      performInitialization();
    }
    switch (INITIALIZATION_STATE) {
      case SUCCESSFUL_INITIALIZATION:
        return StaticLoggerBinder.getSingleton().getLoggerFactory();
      case NOP_FALLBACK_INITIALIZATION:
        return NOP_FALLBACK_FACTORY;
      case FAILED_INITIALIZATION:
        throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
      case ONGOING_INITIALIZATION:
        // support re-entrant behavior.
        // See also http://bugzilla.slf4j.org/show_bug.cgi?id=106
        return TEMP_FACTORY;
    }
    throw new IllegalStateException("Unreachable code");
  }

  private final static void performInitialization() {
    bind();
    if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
      versionSanityCheck();
    }
  }

  private final static void bind() {
    try {
      Set staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
      reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
      // the next line does the binding
      StaticLoggerBinder.getSingleton();
      INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
      reportActualBinding(staticLoggerBinderPathSet);
      emitSubstituteLoggerWarning();
    } catch (NoClassDefFoundError ncde) {
      String msg = ncde.getMessage();
      if (messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) {
        INITIALIZATION_STATE = NOP_FALLBACK_INITIALIZATION;
        Util.report("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".");
        Util.report("Defaulting to no-operation (NOP) logger implementation");
        Util.report("See " + NO_STATICLOGGERBINDER_URL
                + " for further details.");
      } else {
        failedBinding(ncde);
        throw ncde;
      }
    } catch (java.lang.NoSuchMethodError nsme) {
      String msg = nsme.getMessage();
      if (msg != null && msg.indexOf("org.slf4j.impl.StaticLoggerBinder.getSingleton()") != -1) {
        INITIALIZATION_STATE = FAILED_INITIALIZATION;
        Util.report("slf4j-api 1.6.x (or later) is incompatible with this binding.");
        Util.report("Your binding is version 1.5.5 or earlier.");
        Util.report("Upgrade your binding to version 1.6.x.");
      }
      throw nsme;
    } catch (Exception e) {
      failedBinding(e);
      throw new IllegalStateException("Unexpected initialization failure", e);
    }
  }

獲取ILoggerFactory的過程基本可以分為

  • performInitialization() : 完成StaticLoggerBinder的初始化
  • getLoggerFactory() :通過StaticLoggerBinder.getSingleton().getLoggerFactory()獲取對應(yīng)的ILoggerFactory

在整個獲取Logger的過程,StaticLoggerBinder是個非常重要的類,其對象以單例的形式存在。在performInitialization過程中,slf4j會首先查找"org/slf4j/impl/StaticLoggerBinder.class"資源文件,目的是為了在存在多個org/slf4j/impl/StaticLoggerBinder.class時給開發(fā)者report警告信息,接著slf4j會使用StaticLoggerBinder.getSingleton()完成StaticLoggerBinder單例對象的初始化。

slf4j之所以能使用StaticLoggerBinder.getSingleton()是因為logback-classic和slf4j-log4j都按照slf4j的規(guī)定實現(xiàn)了各自的org/slf4j/impl/StaticLoggerBinder.class。那么如果系統(tǒng)中同時存在logback-classic和slf4j-log4j的話,slf4j選擇哪一個呢,答案是隨機(jī)挑選(這是由類加載器決定的,同包同名字節(jié)碼文件的加載先后順序不一定)。

StaticLoggerBinder初始化

logback的StaticLoggerBinder的初始化如下

  void init() {
    try {
      try {
        new ContextInitializer(defaultLoggerContext).autoConfig();
      } catch (JoranException je) {
        Util.report("Failed to auto configure default logger context", je);
      }
      StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext);
      contextSelectorBinder.init(defaultLoggerContext, KEY);
      initialized = true;
    } catch (Throwable t) {
      // we should never get here
      Util.report("Failed to instantiate [" + LoggerContext.class.getName()
          + "]", t);
    }
  }

其中ContextInitializer會完成配置文件例如logback.xml的文件解析和加載,特別要注意的是defaultLoggerContext是LoggerContext的實例,LoggerContext是logback對于ILoggerFactory的實現(xiàn)。

獲取Logger

  public final Logger getLogger(final String name) {

    if (name == null) {
      throw new IllegalArgumentException("name argument cannot be null");
    }

    // if we are asking for the root logger, then let us return it without
    // wasting time
    if (Logger.ROOT_LOGGER_NAME.equalsIgnoreCase(name)) {
      return root;
    }

    int i = 0;
    Logger logger = root;
    Logger childLogger = (Logger) loggerCache.get(name);
  
    if (childLogger != null) {
      return childLogger;
    }
    String childName;
    while (true) {
      int h = Logger.getSeparatorIndexOf(name, i);
      if (h == -1) {
        childName = name;
      } else {
        childName = name.substring(0, h);
      }
      i = h + 1;
      synchronized (logger) {
        childLogger = logger.getChildByName(childName);
        if (childLogger == null) {
          childLogger = logger.createChildByName(childName);
          loggerCache.put(childName, childLogger);
          incSize();
        }
      }
      logger = childLogger;
      if (h == -1) {
        return childLogger;
      }
    }

在logback中,ILoggerFactory的實現(xiàn)是LoggerContext,調(diào)用LoggerContext.getLogger獲取的Logger實例類型為ch.qos.logback.classic.Logger,是org.slf4j.Logger的實現(xiàn)類。獲取Logger的過程可以分為

  • 是否是root,如果是,返回root
  • 從loggerCache緩存中獲取,loggerCache中包含了配置文件中解析出來的logger信息和之前create過的logger
  • 將logger name以"."分割,獲取或者創(chuàng)建的logger,例如com.mujin.lnamp,會創(chuàng)建名為com、com.mujin、com.mujin.lnamp的logger,并將其放入loggerCache然后返回com.mujin.lnamp。logger是root logger的child即logger.parent=ROOT

至此獲取Logger完成,logback的Logger實現(xiàn)類為ch.qos.logback.classic.Logger

集成log4j

slf4j集成log4j需要引入slf4j-api、slf4j-log4j12、log4j三個Jar包,slf4j-log4j12用來起橋接作用。

獲取Logger的過程和logback的過程一樣,唯一不同的是StaticLoggerBinder的實現(xiàn)方式不一樣,StaticLoggerBinder的構(gòu)造方法如下

private StaticLoggerBinder() {
    loggerFactory = new Log4jLoggerFactory();
    try {
      Level level = Level.TRACE;
    } catch (NoSuchFieldError nsfe) {
      Util.report("This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version");
    }
  }

只是新建了Log4jLoggerFactory的實例,Log4jLoggerFactory是ILoggerFactory的實現(xiàn)類。

log4j版的StaticLoggerBinder獲取logger過程如下

public Logger getLogger(String name) {
    Logger slf4jLogger = loggerMap.get(name);
    if (slf4jLogger != null) {
      return slf4jLogger;
    } else {
      org.apache.log4j.Logger log4jLogger;
      if(name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME))
        log4jLogger = LogManager.getRootLogger();
      else
        log4jLogger = LogManager.getLogger(name);

      Logger newInstance = new Log4jLoggerAdapter(log4jLogger);
      Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
      return oldInstance == null ? newInstance : oldInstance;
    }
  }

思路很清晰

  • 從loggerMap中嘗試取出
  • 如果logger name名為root,返回root
  • 使用LogManager.getLogger返回Log4j的Logger實現(xiàn),其類型為 org.apache.log4j.Logger log4jLogger
  • 使用Log4jLoggerAdapter包裝 org.apache.log4j.Logger log4jLogger,使其適配org.slf4j.Logger接口
  • 將Log4jLoggerAdapter嘗試放入loggerMap緩存

那這樣就有個疑問了,log4j的配置文件如何加載的呢?答案在LogManager的靜態(tài)塊中


static {
        Hierarchy h = new Hierarchy(new RootLogger(Level.DEBUG));
        repositorySelector = new DefaultRepositorySelector(h);
        String override = OptionConverter.getSystemProperty("log4j.defaultInitOverride", (String)null);
        if(override == null || "false".equalsIgnoreCase(override)) {
            String configurationOptionStr = OptionConverter.getSystemProperty("log4j.configuration", (String)null);
            String configuratorClassName = OptionConverter.getSystemProperty("log4j.configuratorClass", (String)null);
            URL url = null;
            if(configurationOptionStr == null) {
                url = Loader.getResource("log4j.xml");
                if(url == null) {
                    url = Loader.getResource("log4j.properties");
                }
            } else {
                try {
                    url = new URL(configurationOptionStr);
                } catch (MalformedURLException var5) {
                    url = Loader.getResource(configurationOptionStr);
                }
            }
            if(url != null) {
                LogLog.debug("Using URL [" + url + "] for automatic log4j configuration.");
                OptionConverter.selectAndConfigure(url, configuratorClassName, getLoggerRepository());
            } else {
                LogLog.debug("Could not find resource: [" + configurationOptionStr + "].");
            }
        }

以上會去加載log4j.properties或log4j.xml等配置文件,然后進(jìn)行初始化

總結(jié)

slf4j通過StaticLoggerBinder鏈接log4j/logback,log4j/logback都提供了對應(yīng)的StaticLoggerBinder實現(xiàn),而對于org.slf4j.Logger接口,log4j提供的默認(rèn)實現(xiàn)是Log4jLoggerAdapter,logback提供的實現(xiàn)是ch.qos.logback.classic.Logger。通過以上分析,我們可以回答兩個問題了

  • 如何判斷系統(tǒng)中使用了slf4j日志門面?
  • 可以通過Class.forName("org.slf4j.impl.StaticLoggerBinder"),如果沒有拋出ClassNotFoundException說明使用了slf4j
  • 如何判斷系統(tǒng)使用了slf4j+log4j還是slf4j+logback
  • 可以通過LogFactory.getLogger的返回類型判斷,log4j實現(xiàn)是Log4jLoggerAdapter,logback實現(xiàn)是ch.qos.logback.classic.Logger

基于以上手段,我們可以做出一套適配log4j或者logback的日志記錄工具類了,后續(xù)將有相關(guān)博文給出

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容